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?
unique_ptr is a new facility with a similar functionality, but with improved security. auto_ptr is a smart pointer that manages an object obtained via new expression and deletes that object when auto_ptr itself is destroyed.
auto_ptr is a class template that was available in previous versions of the C++ standard library (declared in the <memory> header file), which provides some basic RAII features for C++ raw pointers. It has been replaced by the unique_ptr class.
A unique_ptr does not share its pointer. It cannot be copied to another unique_ptr , passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved.
In short: Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With