C ++ memory management (new operator / operator new / operator delete / placement new)

new operator

new we usually use the new operator (new operator), the same as sizeof is built into the language, can not change its meaning, function is the same

such as:

string *ps = new string("Memory Management");

Equivalent to

void *memory = operator new(sizeof(string)); // 得到未经处理的内存,为String对象 
call string::string("Memory Management") on *memory; // 调构造函数将字符串放到内存 
string *ps = static_cast<string*>(memory); // 使ps指针指向新的对象

The new operator always do two things:

1. Call the appropriate operator new to allocate memory

2. call the appropriate constructor

The following code:

class T{  
    public:  
    T(){  
        cout << "构造函数。" << endl;  
    }  

    ~T(){  
        cout << "析构函数。" << endl;  
    }  

    void * operator new(size_t sz){  

        T * t = (T*)malloc(sizeof(T));  //operator new就是简单的分配内存即可
        cout << "内存分配。" << endl;  
        return t;  
    }  

    void operator delete(void *p){  
        free(p);  
        cout << "内存释放。" << endl;  
        return;
    }  
};  

int main()  
{  
    T * t = new T(); // 先内存分配 ,再构造函数  
    delete t; // 先析构函数, 再内存释放  
    return 0;  
} 

operation result

operator new

Overloading the new operator, you can change how to allocate memory for the object. new operator calls a function to do the necessary memory allocation, you can rewrite or override this function to change its behavior. new operator to allocate memory for the called function name is operator new.

New operator overloading

void * operator new(size_t sz)
{
    void* pm=malloc(sz);
    return pm;
}

The return type is a type of void * pointers, uninitialized memory, you can write one kind of operator new function, before returning a pointer can be initialized memory to store some value, but generally do not do so. You can add additional parameters overloaded function operator new, but the first argument must be of type size_t. own new type can be calculated corresponding to the size of a pointer type.

Generally do not directly call operator new, but sometimes used, such as in STL:

Test *pt2=(Test*)::operator new(sizeof(Test));
::operator delete(pt2);

It returns a pointer to the object enough to accommodate a Test type of memory. operator new to allocate memory only. And constructors unrelated. Passing a pointer to the unprocessed operator new object is returned to a new operator is working.

such as:

string *ps = new string("Memory Management");

Equivalent to

void *memory = operator new(sizeof(string)); // 得到未经处理的内存,为String对象 
call string::string("Memory Management") on *memory; // 调构造函数将字符串放到内存 
string *ps = static_cast<string*>(memory); // 使ps指针指向新的对象

operate delete

is to delete calls the destructor, then delete operator calls, free up space, it can be seen from the above results run.

They can delete their own overloaded

void operator delete(void *p)
{
    free(p);
}

operator new

Overload new [] operator

void* operator new[](size_t sz)
{
    void *pm=malloc(sz);
    return pm;
}

operator new and operator new functions are allocated only memory, to a new operator new is used, operator new [] is a new [] used, new [] actually assigned multiple than four new bytes for the object quantity

This number four bytes has been added as a void * operator new calling parameter; in the size of, that is to say when the A * ap = new A5 call; time, also called the internal operator new; the effect is to apply 5 * size (a) + 4 bytes of memory. new [] call the object's constructor will each array initialization. Also new [] may be calculated corresponding to the size of their own type of pointer type.

Extra four bytes, the equivalent of cookie, used to record how much to apply, when to call delete [] release can know how much space is released.

operator delete

Overload delete [] operator

void operator delete[](void *p)
{
    free(p);
}

In operator new [] needs of a given size, but delete [] does not require a given size, even to the size, it does not make sense, is not valid, the release time is to read the above mentioned information a cookie to release.

placement new

new two-step walk, allocates memory, after calling the constructor. So, is it possible to maintain a memory, repeated construction destructor? Such multiple intermediate memory allocation may be omitted. As the application of memory have a lot of overhead. C ++ standard was thinking, so they provide placement new, locating new.

int *p=(int*)malloc(sizeof(int)*10);
new(p)int(10);

10 said it would put the first space of p.

void * operator new(size_t, void *location) 
{  
    return location; 
}

It is also a method of using the new operator, the need to use an additional variable (buffer). When a new operator implicitly called operator new function. Pass this variable to it. The called operator new function in addition to the mandatory parameters with size_t, void * pointer must accept the parameters. Pointing to the memory space occupied by the object structure.

If you want a place other elements of the subscript position, you can reload new

void* operator new(size_t sz,void *ptr,int pos)    //第1个参数必须但不需要传递,由new自动计算的,第2个参数传递void*指针,第3个参数传递位置
{
    return &ptr[pos];
}

new(p,3)int(10);    //将10放在下标为3的空间中

Internal mechanisms for realization of new

We all know that new two-step process to complete, but new is how to accomplish these two steps it? 

I thought it was a package inside the new two functions, one is used to allocate memory, and one to call the appropriate constructor.

But in fact not the case, it is not a "hidden" new function, the compiler will automatically rewritten into a new memory allocation function, a constructor. 

In fact, here there is a more essential problem should be noted: the nature of the new keyword, keyword insider compiler operations may differ materially from our imagination. Can be overloaded function, is the operator, the keyword is not overloaded, which is why the operator must have operator overloading in front of reasons. + (Int a), new (int a) is wrong. 

Briefly, in operation of new new compiler will become two parts of the code, allocated memory portion, a portion of the call the constructor.

This can actually be done experimentally validated: 

Join in the above code new T and marked with a breakpoint, then F10 step by step debugging, found first into class operator new, and not after the implementation of new T to the next line, but still remain in this new line, F10 to continue into the constructor. This means that the new T line stayed twice. This means that the compiler does the new T line of code translated into two function calls.

The second way is to directly verify the disassembly view the code (recommended): 

  I can see there are indeed two call, the first call T :: operator new (). The second call T :: T (). Note: The real Compendium no specific function name, only the corresponding address. VS display function name is one of the more convenient features.

  I can see there are indeed two call, the first call T :: operator new (). The second call T :: T (). Note: The real Compendium no specific function name, only the corresponding address. VS display function name is one of the more convenient features.

:: new and new

  There is a built-in global namespace, designed to hide the operator new to allocate memory. The compiler will translate this new keyword default operator new to this and the corresponding constructor.

  However, in some cases, the users themselves will be in a class overloads operator new, in this case, the compiler will use the default class overloaded operator new (essentially because the compiler looks from the namespace from the inside out function you want, choose the first).

  If we want to continue to use the default operator new, it should be written :: new literal meaning is to call the outermost layer in the namespace operator new

 It is worth mentioning that the outermost (also the default) operator new can also be overloaded. In this way we can change the behavior of all parts of the new.

to sum up

C ++ dynamic memory management is performed by the new and delete operators.

Figure explain the meaning of new and delete with a:

new and delete and malloc and free, like, to be used in pairs.

This is the string * s = new string ( "a value"); for internal expression of the phrase:

It can be drawn:

(Initialization of an object) inside the calling sequence new: new - operator new - malloc - Constructor (first space applications, and then call the constructor)

(Initialization several objects) inside the calling sequence new: new - operator new [] - malloc - Constructor (array of all members of the first Application +4 space, each object in the array to call the constructor)

(When a single object delete) delete the object when the call order: delete - destructor - operator delete - free (first calls the destructor, then free space)

(When a plurality of objects delete) delete the object when the call order: delete [] - destructor - operator delete [] - free (first call the destructor for each array object, then release the entire array space, spatial information in a multi-application, four bytes)

new / delete and malloc / free difference between the two

1. They are dynamic memory management portal.

2.malloc / free is a function of C / C ++ Standard Library, new / delete the C ++ operator.

3.malloc / free just dynamically allocated memory space / free space. The new / delete in addition to the allocated space will be calling the destructor to initialize and clean up (clean-members).

4.malloc / free manual calculations and returns a value of type size void *, new / delete their type may calculate the size of a corresponding type of pointer.

The underlying 5.new/delete call malloc / free.

6.malloc / application after free space was sentenced empty, new / delete is not required.

With the type, malloc number with the number of bytes 7.new directly.

Guess you like

Origin www.cnblogs.com/WindSun/p/11445844.html