|
auto_ptr is a class template available in the C++ Standard Library (declared in <memory>) 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.[1] 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.[2]
DeclarationThe auto_ptr class is declared in ISO/IEC 14882, section 20.4.5 as: namespace std { template <class Y> struct auto_ptr_ref {}; template <class X> class auto_ptr { public: typedef X element_type; // 20.4.5.1 construct/copy/destroy: explicit auto_ptr(X* p =0) throw(); auto_ptr(auto_ptr&) throw(); template <class Y> auto_ptr(auto_ptr<Y>&) throw(); auto_ptr& operator=(auto_ptr&) throw(); template <class Y> auto_ptr& operator=(auto_ptr<Y>&) throw(); auto_ptr& operator=(auto_ptr_ref<X> r) throw(); ~auto_ptr() throw(); // 20.4.5.2 members: X& operator*() const throw(); X* operator->() const throw(); X* get() const throw(); X* release() throw(); void reset(X* p =0) throw(); // 20.4.5.3 conversions: auto_ptr(auto_ptr_ref<X>) throw(); template <class Y> operator auto_ptr_ref<Y>() throw(); template <class Y> operator auto_ptr<Y>() throw(); }; } SemanticsThe 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: #include <iostream> using namespace std; int *i = new int; auto_ptr<int> x(i); auto_ptr<int> y; y = x; cout << x.get() << endl; cout << y.get() << endl; 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 Notice that the object pointed by an auto_ptr is destructed using See alsoReferences
External links |
This article is from Wikipedia. All text is available under the terms of the GNU Free Documentation License.
Mercedes Car
This site monitored by SitePinger.net