19

Possible Duplicate:
std::auto_ptr to std::unique_ptr
What C++ Smart Pointer Implementations are available?

Lets say I have this struct:

struct bar 
{ 

};

When I use auto_ptr like this:

void foo() 
{ 
   auto_ptr<bar> myFirstBar = new bar; 
   if( ) 
   { 
     auto_ptr<bar> mySecondBar = myFirstBar; 
   } 
}

then at auto_ptr<bar> mySecondBar = myFirstBar; C++ transfers the ownership from myFirstBar to mySecondBar and there is no compilation error.

But when I use unique_ptr instead of auto_ptr I get a compiler error. Why C++ doesn't allow this? And what is the main differences between these two smart pointers? When I need to use what?

Community
  • 1
  • 1
Maroun
  • 94,125
  • 30
  • 188
  • 241
  • 1
    See http://stackoverflow.com/questions/5026197/what-c-smart-pointer-implementations-are-available – hmjd Nov 20 '12 at 20:32

1 Answers1

47

std::auto_ptr<T> may silently steal the resource. This can be confusing and it was tried to defined std::auto_ptr<T> to not let you do this. With std::unique_ptr<T> ownership won't be silently transferred from anything you still hold. It transfers ownership only from objects you don't have a handle to (temporaries) or which are about to go away (object about to go out of scope in a function). If you really want to transfer ownership, you'd use std::move():

std::unique_ptr<bar> b0(new bar());
std::unique_ptr<bar> b1(std::move(b0));
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380