Obviously, you cannot just do the assignment std::unique_ptr , as their assignment operator is removed. This intentionally forces the programmer to determine what behavior he wants.
- The new item gains ownership of
c_ , the invalid source item. - The new element creates a copy of
c_ , while maintaining the authenticity of the original elements. - The new element shares ownership of
c_ so that both the new and original elements refer to the same object.
In case 1 , what you are looking for is a move constructor, and the default move constructor will work fine. Therefore, you do not need to write any code, you can just do:
A temp; A foo(std::move(temp));
Note that temp not valid after moving it.
In case 2, you need to add your own copy constructor in A to create a copy of the original c_ :
A(const A& a):c_(new C(*(a.c_))){}
After defining this in A you can do:
A foo(A());
Note that this depends on the C functional constructor.
In case 3, you need to fundamentally change A using std::unique_ptr to use std::shared_ptr , so the definition of c_ will be as follows:
std::shared_ptr<C> c_;
Your build of c_ will be identical to what you are already using for std::unique_ptr version of c_ . So, just using standard implementations you could do:
A foo; A bar(foo);
And now foo and bar point to the same C object and share its ownership. This shared object will not be deleted until all shared_ptr referencing it has been deleted.
source share