How to move ownership through unique_ptrs
I have two smart pointers:
Foo *p1 = new Foo;
Foo *p2 = new Foo;
std::unique_ptr<Foo> u1(p1);
std::unique_ptr<Foo> u2(p2);
      
        
        
        
      
    
Now I want to u1
      
        
        
        
      
    have p2
      
        
        
        
      
    . And I want u2
      
        
        
        
      
    to have nothing (or nullptr
      
        
        
        
      
    ). Of course, at the same time p1
      
        
        
        
      
    must be removed gracefully.
What C ++ code should I write to execute it?
Use std::move
      
        
        
        
      
    to apply u2
      
        
        
        
      
    to rvalues, then use move assignment to move u2
      
        
        
        
      
    to u1
      
        
        
        
      
    :
u1 = std::move(u2);
      
        
        
        
      
    
After moving there u2
      
        
        
        
      
    will be nullptr
      
        
        
        
      
    , although this is a special case for unique_ptr
      
        
        
        
      
    , don't expect moving from objects to be in any particular state in general. And, of course, it p1
      
        
        
        
      
    will be gracefully removed.
I recommend that you do not create p1
      
        
        
        
      
    or p2
      
        
        
        
      
    and never have any pointers of your own:
std::unique_ptr<Foo> u1(new Foo);
      
        
        
        
      
    
Or better yet, in C ++ 14:
auto u1 = std::make_unique<Foo>();
      
        
        
        
      
     What you want to do is basically describe the move assignment for unique_ptr
      
        
        
        
      
    , modulo part of the deleter (not relevant here):
u1 = std::move(u2);
      
        
        
        
      
     The two versions below will do the same:
u1 = std::move(u2);
      
        
        
        
      
    
and
u1.swap(u2);
u2.reset(nullptr);
      
        
        
        
      
    
although the former is more efficient. u2
      
        
        
        
      
    will contain nullptr
      
        
        
        
      
    in both cases.
I am also joining the chorus for use std::make_unique
      
        
        
        
      
    in C ++ 14 (more efficient and safer in many cases).