[C++]C++11 shared_ Summary of PTR smart pointer usage

0x00 Preface

There may be grammatical errors and punctuation errors in the text, please understand;

If you find code errors or other problems in the article, please let us know. Thank you!

0x01 manual memory management

In actual C + + development, we may have problems such as sudden crash during program operation due to improper manual memory resource management, or more and more memory occupation found in background monitoring. The specific reasons for improper memory management are as follows:
·Memory resources are not delete d and released in time after they are not used, resulting in memory leakage, resulting in more and more memory resources occupied by programs;
·The memory resource has been released, but the pointer to the block of memory has not changed. The pointer becomes a wild pointer and continues to be used without knowledge;
·After the memory resource is released, it is released again.

Therefore, in order to deal with the above situation, whether we can propose a more friendly memory management mechanism. When we don't need memory resources, the system can recycle itself (garbage collection mechanism). There is such a mechanism in C + +. Auto is used in C++98/03 Standard_ PTR smart pointer to realize the automatic recovery of heap memory. In C++11, auto is abandoned_ PTR, but unique is added_ ptr,shared_ptr and weak_ptr uses these three smart pointers to realize the automatic collection of heap memory.

0x02 shared_ptr

The use of smart pointers is similar to ordinary pointers, but smart pointers release the allocated memory resources by reference counting. This mechanism can avoid memory leakage.

In short, the reference count is an integer value that will be configured for the smart pointer when it applies for heap memory space resources (the initial value is 1. If it is an empty shared_ptr pointer (for example: STD:: shared_ptr < int > P2 (nullptr); STD:: shared_ptr < int > P1;), the initial reference count is 0 instead of 1), If multiple smart pointers point to the memory space, the reference count value will increase. When a smart pointer pointing to the memory space destructs or points to other memory spaces, the reference count will be reduced by 1. If the reference count is 0, it indicates that no pointer points to the space and the heap space will be released.

The above three types of smart pointers are implemented in the form of class templates_ The use of PTR shall be declared as follows:

    #include <memory>
    using namespace std;

shared_ PTR < T > (where T represents the specific data type pointed to by the pointer) is located in the header file < memory > and contained in the namespace std.

shared_ The member methods provided by PTR < T > template class are as follows:

Member's legal namefunction
operator=()Overload the assignment number so that shared of the same type_ PTR smart pointers can be assigned to each other.
operator*()Overload the * sign to get the current shared_ptr the data pointed to by the smart pointer object.
operator->()Overload the - > sign. When the data type pointed to by the smart pointer is a user-defined structure, the specified member inside can be obtained through the - > operator.
swap()Exchange 2 shared of the same type_ Content of PTR smart pointer.
reset()When the function has no arguments, the function will make the current shared_ The reference count of heap memory referred to by PTR is reduced by 1, and the current object is reset to a null pointer; When a newly requested heap memory is passed for the function, the shared of the function is called_ The PTR object takes ownership of the storage space, and the initial value of the reference count is 1.
get()Get shared_ The PTR object contains ordinary pointers inside.
use_count()Return the same as the current shared_ The PTR object (including it) points to all shared objects that are the same_ Number of PTR objects.
unique()Judge the current shared_ Is there no other shared memory in the heap memory pointed to by the PTR object_ The PTR object then points to it.
operator bool()Judge the current shared_ Whether the PTR object is a null smart pointer. If it is a null pointer, false is returned; Otherwise, it returns true.

give an example:

#include <iostream>
#include <string>
#include <memory>

using namespace std;

class Test
{
public:
   
	Test()
	{
		
	}
	Test(string name)
    {
        name_ = name;
        cout << this->name_ << "  constructor" << endl;
    }
    ~Test()
    {
        cout << this->name_ << "  destructor" << endl;
    }

    string name_;
};


int main()
{
    std::shared_ptr<Test> pStr1 = std::make_shared<Test>("object");
    cout << (*pStr1).name_ << endl;
    cout << "pStr1 Reference count:" << pStr1.use_count() << endl;

    std::shared_ptr<Test> pStr2 = pStr1;
    cout << (*pStr2).name_ << endl;
    cout << "pStr1 Reference count:" << pStr1.use_count() << endl;
    cout << "pStr2 Reference count:" << pStr2.use_count() << endl;
    
    int *pInt1 = new int(11);
    std::shared_ptr<int> pInt2 = std::make_shared<int>(11);
    cout << pInt2.unique() << endl; 
	
    std::shared_ptr<int> pInt3 = pInt2 ;
    cout << pInt2.unique() << endl; 
    
    cout << pInt3.use_count() << endl;
    cout << pInt2.use_count() << endl;
	
	cout << endl;
	cout << endl;
	
	std::shared_ptr<Test> p1(new Test);
	cout <<"aa"<< p1.use_count() << endl;
	std::shared_ptr<Test> p2(new Test);
	cout << "bb"<<p2.use_count() << endl;
	p1 = p2;
	cout << "cc"<<p1.use_count() << endl;
	cout << "dd"<<p2.use_count() << endl;

    return 0;
}

Operation results:

above.
Reference documents:
1.https://blog.csdn.net/weixin_42205987/article/details/82946894
2.http://c.biancheng.net/view/7898.html

Keywords: C++ Back-end

Added by dansk on Thu, 11 Nov 2021 11:00:46 +0200