2c + +: new, delete exploration, overview of intelligent pointer, shared & PTR Foundation (Reprint)

new, delete

new, delete is a keyword, like sizeof. Not a function

new and delete do more than malloc and free.

#include <iostream>
#include <vector>
using namespace std;

class A
{
    public:
    A()
    {
        cout <<"A structure"<<endl;
    }
    ~A()
    {
        cout <<"A Destructor of" << endl;
    }
};
int main()
{
    A *pa = new A();//Constructor called
    delete pa; //Destructor will be called
    //new and delete are capable of initializing and releasing (de initializing) the memory allocated on the heap, which are not available for mallloc and free
    return 0;
}

Operator new() and operator delete()

/ / operator new() and operator delete()
    int *pi =new int;
    delete pi;
/ / new does two things: a) allocate memory (allocate memory through operator new())
Call the constructor to initialize the inner push
/ / void *mypointer = operator new (100); / / allocate 100 memory
/ / delete also does two things: a) call the destructor

/ / b) free memory (call operator delete() to free memory)

 

How to record the allocated memory size in basic new


/ / different compilers have different ways to use new internally
/ / int *p = new int; //4 bytes
/ / delete p; / / when deleting, how does the compiler know to recycle 4 bytes: there is a recording mechanism inside new

 

#include <iostream>
#include <vector>
using namespace std;

class A
{
    public:
    A()
    {
        cout <<"A structure"<<endl;
    }
    ~A()
    {
        cout <<"A Destructor of" << endl;
    }

};
int main()
{

    //Apply and release a group
    int *p1 = new int(100); //Allocate 4 bytes to int = 100;
    int *p2 = new int [2] ;//int array, there are two elements, if there is no delete, 8 bytes will be leaked
    delete p1;
    delete []p2;
    //
    A a;
    int ilen = sizeof(a) ;//Class object must have an address, at least one byte of address. '
    cout << ilen << endl;//The result is 1; / / no constructors and destructors
    //Having constructors and destructors also takes up one byte. Because constructors and destructors (member functions) do not occupy the memory of class objects
    //If you add a member variable size, it will become 4 int m ﹐ B;

    //A *pa = new A(); / / leak a byte
    //A *pa2 = new A[2] (); / / leaks 6 bytes instead of 2. Four more bytes
    //Int * P = New Int [2]; / / int array has two bytes, 8 bytes are leaked, and 4 bytes are not extra
    //Question: why do we dynamically allocate memory object array to class item A by 4 bytes, while the built-in type int dynamically allocates memory objects
    //No more 4 bytes?
    int *p3 = new int[2]; 
    A *p4 = new A[2];
    delete p3;
    //Or write delete []p3;
    delete []p4; //2 times of deconstruction
    //Write as dlete p4; report an error
    //So: the four extra bytes are the records of several A objects, which are constructed and released several times. Save the size of the array
    //Built in type int array, no destructor required. Similarly, if a class does not have a custom destructor, you may not need to write []
    //It is recommended to write []. 
    //A *p5 = new A[2]; / / if there is no destructor, 2 bytes are allocated, and 6 bytes are allocated if there is one
    
    //new/delete needs to be paired. If it is not paired, unexpected errors will occur.
     return 0;
}




Intelligent pointer overview

#include <iostream>
#include <vector>
using namespace std;
int main()
{
     
     int *p = new int();
     int *q = p;
     int *r = q;//Only when p q r is not used will this memory be released
     //new and delete should be very careful to prevent premature release and forget release. In a word, it is not easy to use them well
     //p bare pointer: pointer returned directly with new
     //Intelligent pointer: understand the packaging of "naked pointer" and wrap a layer outside the naked pointer; bring advantages after packaging
     //   The most outstanding advantage: smart pointer can "automatically release the memory of the pointed object" 
     //It is recommended to choose smart pointer first.
     
     //There are four smart pointers: std:
      //Auto PTR (c + + 98) the rest is c++11: unique PTR shared PTR weak PTR
      //c++11 is against the use of auto? PTR, which is not easy to use
      //Shared? PTR is a shared pointer. Multiple pointers point to the same object. When the last pointer is destroyed, the object is released
      //The peak PTR is used to assist the shared PTR
      //unique_ptr: exclusive pointer, only one pointer can point to the object at the same time
         //Of course, the ownership of the object can still be transferred.
      //When you forget to delete, the smart pointer helps you delete
     
     return 0;
}

make_shared

It can allocate and initialize an object in dynamic memory (heap), and then return the shared ﹣ PTR that the pointer points to the object

#include <iostream>
#include <vector>
#include <memory> // shared_ptr
using namespace std;


int main()
{
    shared_ptr <int> p = make_shared<int> (100);
    //This shared_ptr points to an integer memory with a value of 100, which is similar to int *p = new int(100);
   shared_ptr <string> pstr = make_shared<string> (5,'a');
   //The string generated by 5 characters a is similar to string pstr (5,'a');
   shared_ptr<int> p2 = make_shared<int> ();//p2 points to an int, and the value stored in int is 0
   p2 = make_shared<int> (100);//p2 points to a new int, in which 100
   //p2 first frees the memory that was just pointed to with a value of 0, and then points to the newly allocated memory.


   auto p5 = make_shared<int> (100);//It is more convenient to use auto.
   //There are some limitations in make ﹐ shared < > and there is no way to customize the remover. I will talk about it later.



    return 0;
}


Shared PTR basis

#include <iostream>
#include <vector>
#include <memory> // shared_ptr
using namespace std;

shared_ptr<int> newABlock(int value)
{
   // return new int(vlaue); / / error, unable to convert int * from new to shared ﹣ PTR
   return shared_ptr <int> (new int(value));
}
int main()
{
    //Shared ownership is not owned by one shared PTR, but by multiple shared PTRs cooperating with each other
    //There is an extra cost
    //How it works: reference count, the copy of each shared ﹣ PTR points to the same memory,
    //Therefore, only when the last shared ﹣ PTR pointer to the memory does not need to point to the object, it will be destructed.

    //Timing of release: a) when the shared uuptr is destructed; b) when the shared uuptr points to other objects.
    //Garbage collection mechanism
    //Class template, used in < > is the type that the pointer can point to, followed by the smart pointer name.
    //Format: shared < PTR < type name pointed to > smart pointer name;
    shared_ptr<int> pitr; //Smart pointer to int, named pitr, but currently null, null pointer, nullptr 

    shared_ptr <int> pi (new int(100));
    //Shared_ptr < int > Pi2 = new int (100); / / without implicit type conversion, this is an error
    
    //Naked pointer can initialize shared_ptr, but it is not recommended to use smart pointer and naked pointer alternately.
      //int *pi2 = new int;
      //Shared_ptr < int > P1 (Pi2); not recommended, prone to problems
    return 0;
}

 

Tags: P4 REST

Posted on Sat, 09 Nov 2019 14:49:29 -0500 by iceman2g