c++

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?


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));
链接地址: http://www.djcxy.com/p/59674.html

上一篇: ptr作为类成员,移动语义无法用clang编译

下一篇: C ++