Common Operations of Boost: scoped_ptr:
It can be simplified as follows:
Namespace boost { Template <typename T> Class scoped_ptr: noncopyable { Public: Explicit scoped_ptr (T * p = 0 ); ~ Scoped_ptr (); Void reset (T * p = 0 ); T & operator * () const;
T * operator-> () Const; T * Get () const; Void swap (scoped_ptr & B ); }; Template <typename T>
Void swap (scoped_ptr <t> & A, scoped_ptr <t> & B );
} |
Its common operations are as follows:
Member Functions |
Function |
Operator *() |
Access the members of the managed object in Reference Form |
Operator-> () |
Access the members of the managed object as pointers |
Get () |
Release managed objects and manage another object |
Swap (scoped_ptr & B) |
Exchange two boost: Objects managed by scoped_ptr |
The following test code demonstrates the basic usage of these functions.
# Include <String> # Include <iostream> # Include <boost/scoped_ptr.hpp> # Include <boost/scoped_array.hpp> # Include <boost/config. HPP> # Include <boost/detail/lightweight_test.hpp> Void test () { // Test scoped_ptr with a built-in type Long * Lp = new Long; Boost: scoped_ptr <long> Sp (LP ); Boost_test (sp. Get () = LP ); Boost_test (Lp = sp. Get ()); Boost_test (& * sp = LP ); * Sp = 1234568901l; Boost_test (* sp = 1234568901l ); Boost_test (* Lp = 1234568901l ); Long * lp2 = new Long; Boost: scoped_ptr <long> SP2 (lp2 ); Sp. Swap (SP2 ); Boost_test (sp. Get () = lp2 ); Boost_test (sp2.get () = LP ); Sp. Reset (null ); Boost_test (sp. Get () = NULL ); } Void main () { Test (); } |
Select boost: scoped_ptr and STD: auto_ptr:
The functions and operations of Boost: scoped_ptr and STD: auto_ptr are similar, how to select between them depends on whether the ownership of the managed object needs to be transferred (for example, whether it needs to be returned as a function ). If this is not required, you can use boost: scoped_ptr to enable the compiler to perform more rigorous checks to find some incorrect assignment operations.