当前位置:网站首页>C + + has no 'garbage collection' function? Intelligent pointer to realize memory management of C + +

C + + has no 'garbage collection' function? Intelligent pointer to realize memory management of C + +

2020-11-10 16:22:39 Muge love programming

This article mainly introduces C++ How to use intelligent pointer to manage memory resources , To help people better understand and use c++ Development , Interested friends can learn about .

1. brief introduction

C++ As a widely used high-level programming language , It's not like Java、C# Languages like this have garbage collection (Garbage Collection ) Mechanism to automatically manage memory , This is also C++ One of the things that has been criticized .C++ In the process of development , Has been committed to solving memory leaks ,C++ Although based on efficiency considerations , There is no garbage collection mechanism , But from C++98 Start , Smart pointer (Smart Pointer) To manage memory resources , To make up for C++ Technical gaps in memory management .

The smart pointer is C++ Programmers are a powerful tool for managing memory , Use smart pointers to manage memory resources , In fact, the application of memory resources by the intelligent pointer to manage , yes RAII An implementation of Technology .RAII yes C++ The father of Bjarne Stroustrup The concept proposed by the professor ,RAII The full name is “Resource Acquisition is Initialization”, It's literally “ Resource acquisition is initialization ”, In other words, get the resource in the constructor , Releasing resources in a destructor . because C++ The language mechanism of the language guarantees , When an object is created , Call constructors automatically , When the object is out of scope, the destructor is called automatically . therefore , stay RAII Under the guidance of , We should use classes to manage resources , Bind a resource to the life cycle of an object .

“ Resource acquisition is initialization ”, When using smart pointers to manage memory resources ,“ resources ” Means by new or malloc Requested memory resources ,“ initialization ” It refers to the use of the requested memory resources to initialize intelligent pointer class objects on the stack . The benefits of using smart pointers to manage memory resources are obvious , At the end of the declaration cycle through the smart pointer object , Call destructors automatically , Complete the release of memory resources in the destructor , That is to automatically call the release code of memory resources , Avoid memory leak caused by forgetting to release memory resources .


 

2. example

Let's take a look at an application by C++11 The introduction of smart pointers unique_ptr To manage memory resources .

#include <memory>

#include <iostream>

using namespace std;

class A

{

public:

    A() {}

    ~A()

    {

        cout<<"A's destructor"<<endl;

    }

    void Hello()

    {

        cout<<"use smart pointer to manage memory resources as far as possible"<<endl;

    }

};

int main()

{

    unique_ptr<A> pA(new A);

    pA->Hello();

    return 0;

}

Program output :

use smart pointer to manage memory resources as far as possible

A's destructor

Visible in main() After function ends , class A The destructor of is called automatically , The memory resource is released .

When creating a smart pointer object , You can also temporarily not specify memory resources , First create a null smart pointer object . Null smart pointer object can not do any operation , But you can use get() Member function to determine whether memory resources exist , If empty, you can specify the memory resource . It is similar to the following operation :

unique_ptr<int> pInt;

if (pInt.get()==nullptr)

{

    pInt.reset(new int(8));

    cout<<*pInt<<endl;

}

Use unique_ptr Smart pointer to manage memory resources , It is the exclusive management of memory resources , That is, the ownership of memory resources cannot be shared , There can only be one... At a time unique_ptr Object occupies a memory resource . If assignment or copy construction occurs , Error will be reported at compile time , because unique_ptr Copy semantics is prohibited , Improved code security .

unique_ptr<int> pInt(new int(8));

unique_ptr<int> pInt1=pInt;   // Compiler error

unique_ptr<int> pInt2(pInt);  // Compiler error

Of course , The ownership transfer of memory resources can be completed through mobile semantics , After transfer , The original intelligent pointer object is changed into a null intelligent pointer object , No more operations can be performed on memory resources , Otherwise, an error will occur at runtime , But we can also use get() Member function for null processing .


 

unique_ptr<int> pInt(new int(8));

unique_ptr<int> pInt1=std::move(pInt);        // Transfer ownership

*pInt=6;                                                                // Assigning a null smart pointer will report a runtime error

if(!pInt.get())                                                     // Empty processing is safer

{

    *pInt=6;

}

Exclusive memory resource management can use unique_ptr To complete , But if you want to share the memory resources , that unique_ptr There's nothing we can do .shared_prt Using reference counting to achieve shared management of memory resources , When the reference count to the memory resource changes to 0 when , The memory resource is released by the last intelligent pointer object that has the right to manage the memory resource .

#include <memory>

#include <iostream>

using namespace std;

class A

{

public:

    A() {}

    ~A()

    {

        cout << "A's destructor" << endl;

    }

    void Hello()

    {

        cout << "use smart pointer to manage memory resources as far as possible" << endl;

    }

};

int main()

{

    shared_ptr<A> spInt(new A);       // Take over memory resources

    cout << "reference count "<<spInt.use_count() << endl;

    shared_ptr<A> spInt1 = spInt; //spInt1 Get the management rights of memory resources

    spInt1->Hello();

    cout << "reference count " << spInt.use_count() << endl;

    spInt1.reset();                     //spInt1 Give up the management of memory resources

    cout << "reference count " << spInt.use_count() << endl;

}

Program compilation run results :

reference count 1

use smart pointer to manage memory resources as far as possible

reference count 2

reference count 1

A's destructor

3. Tips for using smart pointer

Smart pointers enhance security , Avoid potential memory leaks , But we should follow certain rules when using it , To ensure the robustness of the code .

(1)smart_ptr  It's not equal to T*, It can't be used exactly according to T* To use . because smart_ptr It's essentially a class object , An intelligent pointer class object for managing memory resources , and T* It's a pointing type T The pointer to , They can't be converted and assigned at will ;

(2) Using separate statements will newed Object puts a smart pointer , Because the use of temporary smart pointer objects can cause a memory leak . Take the following statement :

process(shared_ptr<A>(new A),foo());

 


 

Actually process() When calling a function, the compiler needs to complete the following three steps process() Get ready for the arguments .

(1) Call function foo();

(2) perform new A expression ;

(3) call shared_ptr Constructors , Initializing the smart pointer object .

actually , Different compilers may execute the three statements in different order , If the compiler will (2.2) Put it in (2.1) Before execution , The order of execution is as follows :

(1) perform new A expression ;

(2) Call function foo();

(3) call shared_ptr Constructors , Initializing the smart pointer object .

If you are calling a function foo() Throw an exception when , that new A The pointer to the heap object generated by the expression will be lost , So there's a memory leak . The solution is to use separate statements to newed Object puts a smart pointer , Doing this :

shared_ptr<A> spA(new A);

process(spA,foo());

That's all C++ How to use intelligent pointer to manage the details of memory resources . See here, are you right about “C++” I have a little new understanding ~


 

If you like this article , Move your little finger , Pay attention to it ~

If you want to be a programmer too , Want to master programming quickly , Here for you to share a learning Penguin circle !

There are senior professional software development engineers , Answer all your doubts online ~C++ introduction “so easy”

Programming learning books :


 

Programming learning video :


 

版权声明
本文为[Muge love programming]所创,转载请带上原文链接,感谢