Auto_ptr vacation

Sometimes, for fleeting moments, I think auto_ptr is cool. But most of the time I admit that there are much simpler methods that make it inconsequential. For example, if I want the object to be freed automatically, even if an exception is thrown, I could update the object and assign auto_ptr. Very cool! But I could more easily create my object as a local variable, and let the stack take care of this (duh!).

So I was not too surprised when I found Google C ++ coding standards prohibiting the use of auto_ptr. Google states that scoped_ptr should be used instead (if a smart pointer is required).

I would like to know if, contrary to my experience, anyone can give good reason when auto_ptr is the best or easiest thing to use. If not, then I believe that I myself forbade using it (following the example of Google).

update . For those who have expressed concern, I do not accept Google standards. For example, against Google’s recommendations, I agree that exception handling should be activated. I also like to use preprocessor macros, such as the printable listing I made. I was struck by the auto_ptr theme.

update2 . It turns out that my answer comes from the two respondents below and from Wikipedia . Firstly, Herb Sutter did show actual use (the original idiom and a collection of objects related to life). Secondly, there are stores where TR1 and boost are not available or prohibited, and only C ++ 03 is allowed. Thirdly, according to Wikipedia, the C ++ 0x specification invalidates auto_ptr and replaces it with unique_ptr. So my answer is: use unique_ptr if it is available to me (on all platforms), otherwise use auto_ptr for the cases that Sutter represents.

+5
source share
6 answers

, , , ++ 03 tr1 boost.

+7

auto_ptr , :

template <typename T>
some_smart_ptr<T> create();

some_smart_ptr ?

shared_ptr , , , ( , ).

, ++ 03 : , , , . auto_ptr . , .

++ 0x, unique_ptr auto_ptr .

+6

std::auto_ptr , ( ) . , std::auto_ptr . , .

std::auto_ptr . , pimpl. , " " . std::auto_ptr , .

+3

auto_ptr , . std::auto_ptr<obj> foo() { foo(); }, obj *foo() . boost:: shared_ptr , .

, - : . boost:: scoped_ptr , .

+2

Well, one of the reasons would be that it is scoped_ptrnot copied, so it’s safer to use and harder to make mistakes. auto_ptrallows you to transfer ownership (for example, passing it another one auto_ptras a constructor parameter). If you need to think about things like transferring ownership, chances are you are better off with a smart pointer, for example shared_ptr.

+1
source

All Articles