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
Why can I not pass a
unique_ptr
into a function?
You cannot do that because unique_ptr
has a move constructor but not a copy constructor. According to the standard, when a move constructor is defined but a copy constructor is not defined, the copy constructor is deleted.
12.8 Copying and moving class objects
...
7 If the class definition does not explicitly declare a copy constructor, one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted;
You can pass the unique_ptr
to the function by using:
void MyFunc(std::unique_ptr& arg)
{
cout << arg->GetVal() << endl;
}
and use it like you have:
or
void MyFunc(std::unique_ptr arg)
{
cout << arg->GetVal() << endl;
}
and use it like:
std::unique_ptr ptr = std::unique_ptr(new A(1234));
MyFunc(std::move(ptr));
Important Note
Please note that if you use the second method, ptr
does not have ownership of the pointer after the call to std::move(ptr)
returns.
void MyFunc(std::unique_ptr&& arg)
would have the same effect as void MyFunc(std::unique_ptr& arg)
since both are references.
In the first case, ptr
still has ownership of the pointer after the call to MyFunc
.