How can I pass a std::unique_ptr
into a function? Lets say I have the following class:
class A
{
public:
A(int val)
{
_val = val
As MyFunc
doesn't take ownership, it would be better to have:
void MyFunc(const A* arg)
{
assert(arg != nullptr); // or throw ?
cout << arg->GetVal() << endl;
}
or better
void MyFunc(const A& arg)
{
cout << arg.GetVal() << endl;
}
If you really want to take ownership, you have to move your resource:
std::unique_ptr ptr = std::make_unique(1234);
MyFunc(std::move(ptr));
or pass directly a r-value reference:
MyFunc(std::make_unique(1234));
std::unique_ptr
doesn't have copy on purpose to guaranty to have only one owner.