Smart Pointers recommendation 34: Manage objects created by new with smart pointers

Source: Internet
Author: User
Tags arrays garbage collection

http://blog.csdn.net/baliguan163/article/details/11720835

recommendation 34: Manage objects created by new with smart pointers We have repeatedly repeated in the previous recommendations: memory leaks are a 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 eye-catching, and in Java has developed into a great tool for memory management, but it in the C + + language development is not smooth, C + + in order to pursue the speed, 20 years of attitude resolutely to exclude it from the standard. I do not know if C + + to increase the difficulty of development in exchange for the implementation of the speed of the practice is the pros or cons. In order to soothe the resentment of C + + programmers who have not garbage collection, C + + has taken a different approach to smart pointer technology, choosing support for this technology and including support in the STL The class of pointer technology gives the C + + programmers a piece of memory management artifact. Smart pointer is the best embodiment of Dr. Stroustrup's RAII (Resource acquisition in initialization). The method uses a pointer class to represent the management logic of the resource and passes the handle (pointer or reference) to the resource through the constructor to the class. When you leave the current scope (scope), the destructor of the object must
is invoked, the code that is reclaimed by the resource that is embedded in the destructor is always executed. The advantage of this approach is that by stripping the logic of the resource collection out of the original code through a particular class, it automatically destroys dynamically allocated objects, which makes the idea clearer and ensures that memory does not leak. A common implementation of this technique is to use reference counting (Reference count). Reference count smart pointer is a lifetime-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 for the class is created, the pointer is initialized and the reference count is set to 1; When an object is created as a copy of another object, it invokes the copy constructor copy pointer and increases the corresponding reference count; When an object is assigned, the assignment operator decreases 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 is increased by the right operand; 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 strong ability, and prudent and wise choice 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 lifecycle of the auto_ptr ends, the resource of the object to which it is directed is automatically freed, without having to explicitly call the delete, and the object pointer's operation remains the same. 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, for example:
Std::auto_ptr<int> iptr;
It is like a null pointer, not pointing to any object, so it cannot be manipulated, but it can be judged by the get () function to point to the address of the object:
if (iptr.get () = = 0)//does not point to any object
{
Iptr.reset (new Int (2011)); Point to an object
}
Auto_ptr can also be built using another auto_ptr, but it is 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 release of the resource to the object, but passes the baton to the SPTR2 's hand, SPtr1 loses the right to use the String class member function, so in the Judgment Sptr1->empty () When the program crashes. The AUTO_PTR resource maintenance action is done in a inline way, and the code is extended at compile time, so using it does not sacrifice efficiency. Although the auto_ptr pointer is a Raii object, can bring us a lot of convenience, but its shortcomings are also not to be underestimated: auto_ptr objects can not be used as an element of STL containers, so the convenience of both can not be owned. This major flaw has angered STL loyalists. Auto_ptr lacks support for dynamically configured arrays, and if used to manage these arrays, the results are dire and unpredictable. The auto_ptr will take place when it is replicated. As the core of C + + garbage collection mechanism, Smart pointer must be strong enough to have industrial strength and ensure security. But the auto_ptr in the STL is like the fools who can't afford to help, unbearable to use. In such cases, the C + + Standard Committee naturally needs to consider introducing a new smart pointer. The Boost series smart pointers developed by boost organization, which is sponsored by the C + + Standard Committee Library team, are most famous. In addition, there are smartptr, atl-provided ccomptr and CComQIPtr provided by the Loki library. 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 Auto_ptr. UNIQUE_PTR provides most of the features of Auto_ptr, the only exception being auto_ptr unsafe, implicit left-value removal, and unique_ptr can be stored in c++0x-raised containers that are aware of moving. There are five 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 supports extensions, which are recommended for most 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 the vector is destroyed, its element-smart pointer object is destroyed unless the object is otherwise intelligently
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 reference strvec[0]
cout<<*strptr<<endl; STRVEC[0] still valid
The boost smart pointer also supports arrays, and the Boost::scoped_array and Boost::shared_array objects point to dynamically configured arrays. Boost's smart pointers, while enhancing security and handling potential dangers, should be used with certain rules to ensure that the code is 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.
You need to explicitly write smart_ptr<t> tptr<new t> when creating a smart pointer. It is forbidden to assign a T * to a smart pointer. Tptr should not be empty using TPTR = NULL, the member function of the smart pointer class should be used.
Rule 2: Do not use a temporary Share_ptr object
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) Invoke the Boost::shared_ptr constructor.
(3) Call function Isallready ().
Because of the uncertainty of the order in which the function parameters are evaluated, if the call to Isallready () occurs between two other processes, and it happens to have an exception, then the memory returned by new A is lost, resulting in a memory leak. Because the returned pointer is not deposited on the boost::shared_ptr that we expect to prevent a resource leak. The way to avoid this problem is to not use a temporary Share_ptr object, instead of using a local variable to implement the object created in a separate statement into the smart pointer:
Boost::shared_ptr<a> PA (New A)
Processobject (PA, Isallready ());
If this is omitted, a subtle resource leak can occur when an exception occurs.
Keep in mind: Always remember RAII principles, using smart pointers to help us manage dynamically configured memory can be a great convenience, but we need to make choices carefully and wisely.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.