Learning Boost 5
Smart Ptr
The top 5 smart pointers provided in Boost. They are:
l Scoped_PTR exclusive pointer
l Scoped_Array exclusive array
l Shared_PTR reference count pointer
l Shared_Array reference count array
l WEAK_PTR Shared_PTR's weak pointer (not participating in reference count)
l Intrusive_PTR Custom reference count pointer
Scoped_ptr and scoped_array
For scoped_ptr and scoped_array, it is not possible to copy construct and assignment (copy constructor and Operator = all private members). So they don't pass the ownership of the pointer as Auto_Ptr, but exclusively owned the right, until the destruction of the object (when Scoped_PTR, the Scropted_Array destructor, the object to be directed).
structure:
Scoped_ptr
Scoped_ptr
Scoped_Array
Scoped_Array
Scoped_ptr uses new T or NULL to initialize the object. Scoped_array uses new T [] or NULL to initialize the object.
The default constructor is initialized using null.
access:
Scoped_ptr Heavy loaded Operator * and Operator-> operators, and Scoped_Array heavyloaded the Operator [] subscript operator. Use these operators to operate the objects you point to. They can get the original pointer through the T * GET () member function.
E.g:
Scoped_Array
STRCPY (Str.get (), "Hello");
COUT << STR [0] << Str [4] << endl; // Output HO
Void Reset (T * P = 0)
Reset is used to reset the object pointing to the pointer. When the RESET is called, scoped_ptr or scoped_array will first delete the original pointing object (if not point to null). The Reset parameters and their constructor are the same, must be new T (or new t []) or NULL.
SWAP
Swap global functions and SWAP member functions, swap two objects that two smart pointers. E.g:
Scoped_ptr
Scoped_ptr
SWAP (A, B); // At this point, a point to NULL, B pointing to an int
Bool
Scoped_ptr and scoped_array can be implicit to the Bool type, returning false when pointing null, otherwise returns true.
Types of
Type T in Scoped_PTR
And scoped_ptr
Shared_ptr and Shared_Array
Shared_ptr and Shared_Array are intelligent pointers that are referenced.
Let's only describe the use of Shared_PTR.
structure:
There are 6 constructor for Shared_Ptr
Shared_ptr (Y * P);
The most common constructor, P must be a new y of the pointer or NULL. Note that the type of P here is Y *, rather than T * in Shared_PTR
Struct a
{
A () {cout << "a construct" << endl;
~ A () {cout << "a destory" << endl;
}
int main ()
{
Shared_ptr
Return 0;
}
/ *
Program output:
A construct
A destroy
This shows that a correct destructor is not destructed because of Shared_Ptr
Void
Del
(void * p) {delete p;} This is wrong
* /
Shared_ptr (Y * P, D D);
Ibid. D is an imitation function that destructure P, for example:
Template
Void my_delete (t * p)
{
Delete P;
}
int main ()
{