- Auto ptr
auto_ptr is a template class available in the
C++ Standard Library (declared in) that provides some basic RAII features for C++ raw pointers. The auto_ptr template class describes an object that stores a pointer to an allocated object of type Type* that ensures that the object to which it points gets destroyed automatically when control leaves a scope. [cite web |url=http://msdn2.microsoft.com/en-us/library/ew3fk483.aspx |publisher=Microsoft |title=auto_ptr Class |accessdate=2006-09-27]
The shared_ptr template class proposed in Technical Report 1 and available in the
Boost library can be used as an alternative to auto_ptr for collections with ownership semantics. [cite web |url=http://www.ddj.com/dept/cpp/184401839 |publisher=Dr. Dobb's |title=Collecting Shared Objects |date=2004-07-01 |accessdate=2006-09-27]Declaration
The auto_ptr class is declared in
ISO/IEC 14882 , section 20.4.5 as:emantics
The auto_ptr has semantics of strict ownership, meaning that the auto_ptr instance is the sole entity responsible for the object's lifetime. If an auto_ptr is copied, the source loses the reference. For example:This code will print a NULL address for the first auto_ptr object and some non-NULL address for the second, showing that the source object lost the reference during the assignment ("="). The raw pointer
i
in the example should not be deleted, as it will be deleted by the auto_ptr that owns the reference.Notice that the object pointed by an auto_ptr is destructed using
operator delete
; this means that you should only use auto_ptr for pointers obtained withoperator new
. This excludes pointers returned bymalloc/calloc/realloc
andoperator new []
.ee also
*
Smart pointer References
External links
* [http://www.gotw.ca/publications/using_auto_ptr_effectively.htm Using
auto_ptr
effectively]
* [http://cprogramming.com/tutorial/auto_ptr.html Avoiding Memory Leaks withauto_ptr
]
* Article " [http://gethelp.devx.com/techtips/cpp_pro/10min/10min1199.asp Using theauto_ptr
Class Template to Facilitate Dynamic Memory Management] " byDanny Kalev
* Article " [http://codeproject.com/KB/cpp/COAP.aspx Container ofauto_ptr
] " byZeeshan Amjad
* [http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.0/classstd_1_1auto__ptr.htmlauto_ptr
Class Template Reference from GNU libstdc++]
* [http://www.roguewave.com/support/docs/sourcepro/edition9/html/stdlibref/auto-ptr.htmlauto_ptr
reference from Rogue Wave]
Wikimedia Foundation. 2010.