Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique_ptr VS auto_ptr [duplicate]

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?

like image 943
Maroun Avatar asked Nov 20 '12 20:11

Maroun


People also ask

What is the difference between auto_ptr and unique_ptr?

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.

What replaces auto_ptr?

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.

Can you copy a unique_ptr?

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.

Why would you choose shared_ptr instead of unique_ptr?

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.


1 Answers

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));
like image 88
Dietmar Kühl Avatar answered Sep 29 '22 18:09

Dietmar Kühl