C + + Smart pointer detailed

Source: Internet
Author: User

C + + Smart Pointer detailed

 

First, Introduction

Because the C + + language does not have an automatic memory recovery mechanism, the programmer will manually delete each new memory. The programmer forgets to delete, the process is too complex, resulting in no delete, and the exception causes the program to quit prematurely, and it is not uncommon to not execute the delete.

Using smart pointers can effectively alleviate such problems, this article mainly explains the use of smart pointers. Includes:std::auto_ptr, Boost::scoped_ptr, Boost::shared_ptr, Boost::scoped_array, Boost::shared_array, Boost::weak_ PTR, boost:: intrusive_ptr. you might think that so many smart pointers are really necessary to solve new and delete matching problems. After reading this article, I think your heart will naturally have the answer.

Here are the 7 smart pointers (SMART_PTR) that are explained in order.

second, the specific use

1 , Umbrella

For the compiler, the smart pointer is actually a stack object, not a pointer type, and the smart pointer releases its managed heap memory through the destructor at the end of the stack object lifetime. All smart pointers overload the "operator->" operator, returning directly to the object's reference to manipulate the object. Accessing the smart pointer The original method uses the "." Operator.

Access to the bare pointers contained by the smart pointer can be used with the Get () function. Because the smart pointer is an object, the if (My_smart_object) is always true, and to determine whether the naked pointer of the smart pointer is empty, you need to judge this: if (My_smart_object.get ()).

The smart pointer contains the reset () method, and if you do not pass the parameter (or pass NULL), the smart pointer frees the currently managed memory. If you pass an object, the smart pointer releases the current object to manage the new incoming object.

We write a test class to assist in parsing:

Class Simple {

Public

simple (int param = 0) {

Number = param;

Std::cout << "simple:" << number << Std::endl;

}

~simple () {

Std::cout << "~simple:" << number << Std::endl;

}

void Printsomething () {

Std::cout << "printsomething:" << info_extend.c_str () << Std::endl;

}

Std::string info_extend;

int number;

};

 

2 , Std::auto_ptr

Std::auto_ptr belong to STL, of course namespace STD, include header file #include <memory> can use. Std::auto_ptr can easily manage a single heap of memory objects.

We start with the code analysis:

void Testautoptr () {

Std::auto_ptr<simple> My_memory (New Simple (1)); Create object, Output: simple:1

if (My_memory.get ()) {//To determine whether the smart pointer is empty

My_memory->printsomething (); To invoke a function in a smart pointer object using operator->

My_memory.get ()->info_extend = "addition"; Use Get () to return the bare pointer, and then assign values to the inner object

My_memory->printsomething (); Print again, indicating success of the above assignment

(*my_memory). Info_extend = "other"; Use operator* to return the inner object of the smart pointer, and then use the "." Calling functions in a smart pointer object

My_memory->printsomething (); Print again, indicating success of the above assignment

}

}//My_memory stack object is about to end lifetimes, the destructor heap object simple (1)

The results of the execution are:

Simple:1

Printsomething:

Printsomething:addition

Printsomething:addition Other

~simple:1

All of the above for the normal use of std::auto_ptr code, everything seems to be good, anyway we do not have to show the use of the damn Delete.

In fact, we look at another example as follows:

void TestAutoPtr2 () {

Std::auto_ptr<simple> My_memory (New Simple (1));

if (My_memory.get ()) {

Std::auto_ptr<simple> My_memory2; Create a new My_memory2 object

My_memory2 = my_memory; Copy the old my_memory to My_memory2.

My_memory2->printsomething (); Output information, replication successful

My_memory->printsomething (); Collapse

}

}

Finally, as the code led to a crash, such as on the code in absolute accordance with C + + programming ideas, actually collapsed, follow the std::auto_ptr source, we see, the culprit is "My_memory2 = my_memory", this line of code, My_memory2 completely captured my _memory memory management ownership, resulting in my_memory dangling, resulting in a crash when used last.

Therefore, when using std::auto_ptr, you must never use the "operator=" operator. As a library, do not allow users to use, do not explicitly reject [1], how many would feel a little unexpected.

After watching Std::auto_ptr's first example, let's look at one more:

void TestAutoPtr3 () {

Std::auto_ptr<simple> My_memory (New Simple (1));

if (My_memory.get ()) {

My_memory.release ();

}

}

The results of the execution are:

Simple:1

See anything out of the ordinary? The object we created was not destructor, no output "~simple:1", causing memory leaks. When we don't want my_memory to survive, we call the release () function to free up memory, which results in memory leaks (in a memory-constrained system, if my_memory takes up too much memory, we consider returning it immediately after use, rather than waiting until My_memory Returned only after the end of the life cycle.

The correct code should be:

void TestAutoPtr3 () {

Std::auto_ptr<simple> My_memory (New Simple (1));

if (My_memory.get ()) {

simple* temp_memory = My_memory.release ();

Delete temp_memory;

}

}

Or

void TestAutoPtr3 () {

Std::auto_ptr<simple> My_memory (New Simple (1));

if (My_memory.get ()) {

My_memory.reset (); Freeing My_memory Internal managed memory

}

}

The original std::auto_ptr release () function simply yields memory ownership, which clearly does not conform to C + + programming ideas.

Summary: Std::auto_ptr can be used to manage the memory of individual objects, but please note the following points:

(1) Try not to use "operator=". If used, do not use the previous object again.

(2) Remember that the release () function does not free objects, only returns ownership.

(3) Std::auto_ptr is best not to pass as a parameter (the reader can write the code to determine why not).

(4) Because of the "operator=" Problem of std::auto_ptr, the object of its management cannot be put into std::vector and other containers.

(5) ...

There are a lot of restrictions on the use of a std::auto_ptr, can not be used to manage the heap memory array, this should be your current thinking of things, I also think that a lot of restrictions, which day a careless, it caused the problem.

Because STD::AUTO_PTR caused a lot of problems, some of the design is not very consistent with C + + programming ideas, so triggered the following boost smart pointers, boost smart pointers can solve the problem.

Let's keep looking down.

3 , Boost::scoped_ptr

Boost::scoped_ptr belongs to boost library, defined in namespace boost, contains header files #include <boost/smart_ptr.hpp> can be used. Boost::scoped_ptr, like Std::auto_ptr, can easily manage a single heap of memory objects, in particular, boost::scoped_ptr exclusive ownership, to avoid std::auto_ptr annoying a few problems.

Let's start by analyzing the code:

void Testscopedptr () {

Boost::scoped_ptr<simple> My_memory (New Simple (1));

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.