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?
Disadvantages of pointers:- 1)we can access the restricted memory area. 2) Pointers require one additional dereference, meaning that the final code must read the variable's pointer from memory, then read the variable from the pointed-to memory. This is slower than reading the value directly from memory.
One of the advantages of smart pointers is, that they ensure due to RAII, that the actual object is deleted. When using a raw pointer, you need to have a delete for every possible exit point, and still an exception will lead to a memory leak. Smart pointers will also free the memory if an exception occurs.
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.
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 c.l.c++.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.
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