http://blog.csdn.net/baliguan163/article/details/11720835
recommendation 34: Use smart pointers to manage objects created with new In the previous recommendation, we are constantly repeating: memory leaks are a big and big problem. Many techniques have been developed to address this problem, such as garbage Collection (garbage collection), Smart Pointer (smart pointers), and so on. Garbage collection technology has been quite noticeable, and in Java has developed mature, become a big tool for memory management, but its development in the C + + language is not smooth, C + + in order to pursue the speed of operation, 20 years of attitude resolutely to exclude it from the standard. I don't know if C + + is going to be good or bad by increasing the difficulty of development in exchange for execution speed. In order to calm down because there is no garbage collection of the C + + Programmer's resentment, C + + to smart pointer technology took a different attitude, it chose to support this technology, and included in the STL support Smart The class of pointer technology gives C + + programmers a piece of memory management artifact. Smart pointer is the best embodiment of RAII (Resource acquisition in initialization), which Dr. Stroustrup has admired. The method uses a pointer class to represent the management logic for the resource and passes a handle (pointer or reference) to the resource through the constructor to the class. When you leave the current scope (scope), the object's destructor must
is called, so the code that is embedded in the destructor for the resource recycling will always be executed. The advantage of this approach is that because the logic of resource recycling is stripped out of the original code by a particular class, the dynamically allocated objects are automatically destroyed, which makes the idea clearer and ensures that memory is not compromised. One of its common implementation techniques is the use of reference counts (Reference count). A reference count smart pointer, which is a life-time managed object that has a reference counter inside it. When the internal reference count is zero, these objects automatically destroy their own smart pointer classes. Each time a new object of the class is created, the pointer is initialized and the reference count is set to 1, and when the object is created as a copy of another object, it invokes the copy constructor to copy the pointer and increments the corresponding reference count; When an object is assigned, the assignment operator reduces the reference count of the object referred to by the left operand If the reference count is reduced to 0, the object is deleted and the reference count of the object referred to by the right operand is increased; when the destructor is called, the constructor reduces the reference count until the count is 0, freeing the object space. Smart pointer has a very powerful ability, and prudent and sensible choices can bring us great convenience. As mentioned earlier, the STL contains a class that supports smart pointer technology, which is the smart pointer: auto_ptr. To use AUTO_PRT, first include the memory header file:
#include <memory>
Auto_ptr can point to an object created with new, and when the life cycle of the auto_ptr ends, the resource of the object it points to is automatically freed, without having to explicitly invoke delete, and the object pointer is still in operation. For example:
Class A
{
Public
A () {}
~a () {}
void Hello ()
{
std::cout<< "Hello Smart Pointer";
}
};
int main ()
{
Std::auto_ptr<a> PA (New A ());
Pa->hello ();
return 0;
}
Of course, you can also create a auto_prt that does not point to any object, such as:
Std::auto_ptr<int> iptr;
It is like a null pointer that does not point to any object, so it cannot be manipulated, but it can be determined by the get () function to point to the address of the object:
if (iptr.get () = = 0)//not pointing to any object
{
Iptr.reset (new Int (2011)); Point to an object
}
Auto_ptr can also be created using another auto_ptr, but it is very important to be careful that this can result in a transfer of ownership, such as:
auto_ptr< string> sPtr1 (New String ("Smart Pointer"));
auto_ptr< string> sPtr2 (SPTR1);
if (!sptr1->empty ())
cout<<*sptr1<< Endl;
When using SPTR1 to establish SPTR2, SPTR1 is no longer responsible for the resource release of the object, but passes the baton to SPTR2 's hand, SPtr1 loses the right to use the String class member function, so in the Judgment Sptr1->empty () When the program crashes. Auto_ptr's resource maintenance action is done inline, and the code is expanded at compile time, so using it does not sacrifice efficiency. Although the auto_ptr pointer is a Raii object, it can bring us a lot of convenience, but its shortcomings are also not to be underestimated: Auto_ptr object is not an element of the STL container, so the convenience of the two can not be owned at the same time. This major flaw has made the loyal followers of STL angry. Auto_ptr lacks support for dynamically configured arrays, and if it is used to manage these arrays, the result is horrible and unpredictable. Auto_ptr a transfer of ownership occurs when it is copied. Smart pointer, as the core of the C + + garbage collection mechanism, must be strong, industrial, and secure. But the auto_ptr in the STL is like the fools that can't afford, unbearable big use. In such cases, the C + + Standards Committee naturally needs to consider introducing new smart pointers. The Boost series smart pointers developed by the C + + Standards Committee Library Working Group are the most famous. In addition to this, there are smartptr provided by the Loki Library, CComPtr and ccomqiptr provided by ATL. The good news is that the auto_ptr pointer was discarded in the new C + + standard C + + 11, which was just passed in September in 2011, and replaced by two new pointer classes: shared_ptr and unique_ptr. SHARED_PTR is simply a reference counting pointer, unique_ptr is used to replace the auto_ptr. UNIQUE_PTR provides most of the features of the auto_ptr, the only exception being Auto_ptr's unsafe, implicit left-hand removal, while unique_ptr can be stored in c++0x-raised containers that can detect moving movements. There are five kinds of smart pointers in boost: Scoped_ptr, Scoped_array, shared_ptr, Shared_array, weak_ptr, the most useful of which is shared_ptr, which takes a reference count and is thread-safe , and also supports extensions, which are recommended for most use cases.
BOOST::SHARED_PTR supports STL containers:
typedef boost::shared_ptr<string> CSTRINGPTR;
std::vector< cstringptr > Strvec;
Strvec.push_back (Cstringptr (New string ("Hello")));
When a vector is destroyed, its element-smart pointer object is destroyed unless the object is otherwise intelligently
The pointer reference, as shown in the following code fragment:
typedef boost::shared_ptr<string> CSTRINGPTR;
std::vector< cstringptr > Strvec;
Strvec.push_back (Cstringptr (New string ("Hello")));
Strvec.push_back (Cstringptr (New string ("Smart"));
Strvec.push_back (Cstringptr (New string ("Pointer"));
Cstringptr strPtr = strvec[0];
Strvec.clear (); Strvec empty, but retains strptr referenced strvec[0]
cout<<*strptr<<endl; Strvec[0] still works
The boost smart pointer also supports arrays, and the Boost::scoped_array and Boost::shared_array objects point to a dynamically configured array. Boost's smart pointers, while enhancing security and dealing with potential dangers, should be followed by certain rules when we use them to ensure that the code is more robust.
Rule 1:smart_ptr<t> is different from t*
Smart_ptr<t> 's real identity is actually an object, an object that manages a dynamic configuration object, and t* is a pointer to an object of type T, so it is not possible to blindly convert a t* and a smart pointer type smart_ptr<t> to each other.
When creating a smart pointer, you need to explicitly write out smart_ptr<t> tptr<new t>. It is forbidden to assign T * to a smart pointer. Tptr should not be empty using TPTR = NULL, and the member function of the smart pointer class should be used.
Rule 2: Do not use temporary SHARE_PTR objects
As shown below:
Class A;
BOOL Isallready ();
void Processobject (boost::shared_ptr< a> PA, bool isReady);
Processobject (Boost::shared_ptr (new A), Isallready ());
Before calling the Processobject function, the C + + compiler must complete three things:
(1) Execute "new A".
(2) Call the Boost::shared_ptr constructor.
(3) Call function Isallready ().
Because of the uncertainty of the Order of evaluation of the function parameters, if the call Isallready () occurs in the middle of the other two processes, and it happens to be an exception, then the memory returned by new A will be lost, and then a memory leak occurs. Because the returned pointer is not stored on the boost::shared_ptr we expect to be able to prevent a resource leak. The way to avoid this problem is not to use a temporary Share_ptr object, instead of using a local variable, which in a separate statement will be stored in the smart pointer with the object created by new:
Boost::shared_ptr<a> PA (New A)
Processobject (PA, Isallready ());
If you neglect this, it can cause subtle resource leaks when an exception occurs.
Remember: Always keep in mind the RAII principle, using smart pointers to help us manage dynamically configured memory can bring us great convenience, but we need to make a careful and sensible choice.