Reputation: 18541
I have a std::unique_ptr<T>
object and a library function that takes T&
as a parameter. This function will change T
object data.
What is the better way to pass the std::unique_ptr<T>
to that function ? Is the above code correct ? Is there a better approach ?
#include <iostream>
#include <string>
#include <memory>
class Test {
public:
std::string message = "Hi";
};
void doSomething(Test& item)
{
item.message = "Bye";
}
int main()
{
std::unique_ptr<Test> unique = std::unique_ptr<Test>(new Test());
std::cout << unique->message << " John." << std::endl;
doSomething(*unique.get());
std::cout << unique->message << " John." << std::endl;
}
Upvotes: 3
Views: 1146
Reputation: 154025
The standard library smart pointers are supposed to be used like raw pointers when it comes to dereferencing the pointer. That is, you'd simply use
std::unique_ptr<Test> unique(new Test());
std::cout << unique->message << " John.\n";
doSomething(*unique);
I included the declaration to show the simplified use and one output to emphasize not to use std::endl
.
Upvotes: 6
Reputation: 65770
You don't need to call get
, just dereference:
doSomething(*unique);
It is best to pass around references to the stored object rather than passing the std::unique_ptr
around by reference, as the lifetime and storage of an object shouldn't need to be communicated to every function using that object.
Upvotes: 11