Advantages/disadvantages of auto pointers

What are the advantages and disadvantages of using auto pointers (auto_ptr), compared to ordinary pointers? I've heard it does automatic releasing of memory but how come it is not used often?


The main drawback of std::auto_ptr is that it has the transfer-of-ownership semantic. That makes it impossible to store std::auto_ptr in STL containers because the containers use the copy constructor when you store or get an element.

Also, another important aspect that i have noticed about the std::auto_ptr is that they cannot serve in the use of PIMPL idiom. This is because, they require the complete definition of the wrapped class's destructor. See this thread on clc++.m for more detailed discussion.

Update : Transfer of ownership

class Test {};
std::auto_ptr<Test> ap_test_1(new Test);
std::auto_ptr<Test> ap_test_2(new Test);

ap_test_2 = ap_test_1;  // here ap_test_1's ownership is transferred i.e. ap_test_2 is the 
                        // new owner and ap_test_1 is NULL.

See this thread on Herb Sutter's site for more details on what this means when used in a STL container used by STL algorithms.


Smart pointers are used often in C++, though perhaps not as often as they should be. The std::auto_ptr has a few problems (you can't use it in Standard Library collections, for example), but there are many others. The most popular of these are the ones that come with the Boost library, and which will be part of the next C++ standard - you should take a look.

Note that smart pointers are mostly about ownership, and deleting dynamically created objects. If you don't have dynamically created objects, you don't normally want smart pointers:

{
  int i = 42;
  auto_ptr <int> p( & i );   // bad!
}

You really don't want to do this, as when the autopointer goes out of scope, it will attempt to delete i. Unfortunately, i was not created dynamically, so bad things will happen. So you need both kinds of pointer, smart and normal, in most C++ programs.


Don't confuse auto pointers (std::auto_ptr) with the family of smart pointers (notably std::auto_ptr, boost::scoped_ptr and boost::shared_ptr).

I pretty much never use auto pointers because, most of the time, i'd rather use references. The only time when i do is for member variables that can't be instantiated in the constructor of the object.

On the contrary, smart pointers are very powerful, but that's not your question, i guess :)

链接地址: http://www.djcxy.com/p/14032.html

上一篇: 堆成员/栈上的类成员分配?

下一篇: 自动指针的优点/缺点