New, operator new and placement New in C + +

Source: Internet
Author: User

Tag: Manipulate your own out to perform flexible set PAC presence space

Ext.: http://www.cnblogs.com/luxiaoxun/archive/2012/08/10/2631812.html

New/delete and operator New/operator Delete

New Operator/delete operator is the new and delete operators, and operator New/operator Delete is a function.

New operator

    • Call operator new to allocate enough space and call the constructor of the related object
    • Can not be overloaded

operator NEW

    • Only the required space is allocated, and the constructor of the related object is not called. When the required allocated space is not met, the

      1. If there is a new_handler, call New_handler, otherwise
      2. If no exception is required (expressed in the nothrow parameter), the BAD_ALLOC exception is executed, otherwise
      3. Returns 0
    • can be overloaded

    • When overloaded, the return type must be declared as void*

    • When overloaded, the first parameter type must be the size (in bytes) of the allocated space for the expression request, and the type is size_t

    • When overloaded, other parameters can be taken

Delete is similar to delete operator

#include <iostream>#include <string>using namespace std;class X{public:    X() { cout<<"constructor of X"<<endl; }    ~X() { cout<<"destructor of X"<<endl;}    void* operator new(size_t size,string str)    {        cout<<"operator new size "<<size<<" with string "<<str<<endl;        return ::operator new(size);    }    void operator delete(void* pointee)    {        cout<<"operator delete"<<endl;        ::operator delete(pointee);    }private:    int num;};int main(){    X *px = new("A new class") X;    delete px;    return 0;}

x* px = new X; New in the line code is new operator, which invokes operator new in class X, allocates space for the object of the class, and then invokes the constructor of the current instance.

Delete px; The delete in the line code is delete operator, which invokes the destructor for the instance, and then calls the operator delete in class X to free up the space occupied by the instance.

The behavior of new operator and delete operator is not and should not be changed, which is a commitment made by the C + + standard. And operator new and operator delete and the C language of malloc and free correspond, only responsible for allocating and freeing space.

However, the space allocated using operator new must be freed using operator delete, not free, because they are not registered in the same way as memory usage. The reverse is also the same. You can reload operator new and operator delete to implement different requirements for memory management, but you cannot overload the new operator or delete operator to change their behavior.

Why is it necessary to write your own operator new and operator delete? The answer is usually: for efficiency. The default operator new and operator Delete are very versatile, and this flexibility makes it possible to further improve its performance in certain situations. This is especially true in applications that need to dynamically allocate large but small objects. Refer to the second chapter, "Effective C + +" for memory management.

The meaning of Placement new

placement New is a standard, global version of the overloaded operator new , which cannot be replaced by custom versions (unlike the normal version of operator new AND operator delete can be replaced).

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

The result is that the user is allowed to put an object in a specific place, reaching the effect of invoking the constructor. Unlike other normal new, it has another parameter in parentheses. Like what:

Widget * p = new Widget; //ordinary newpi = new (ptr) int;      //placement new

The parameter ptr in parentheses is a pointer to a memory buffer, and placement new will allocate an object on the buffer. The return value of Placement new is the address of the constructed object (such as the pass parameter in parentheses). Placement New is primarily intended for applications where time is very high, because the time allotted for these programs is deterministic, for long-running programs that are not interrupted, and for executing a garbage collector (garbage collector).

New, operator new and placement new differences
    • NEW: cannot be overloaded, its behavior is always consistent. It first calls operator new to allocate memory, and then calls the constructor to initialize that piece of memory. The new operator executes the procedure:

      1. Call operator new to allocate memory;
      2. Call the constructor to generate the class object;
      3. Returns the corresponding pointer.
    • Operator NEW: To implement different memory allocation behavior, operator new should be overloaded instead of new.

      operator new is like Operator +, which can be overloaded. If operator new is not overloaded in the class, then the call is global: operator new to complete the heap allocation.

      Similarly, operator new[], operator delete, operator delete[] can also be overloaded.

    • Placement NEW: Just one version of operator new overload. It does not allocate memory, but returns a pointer to a memory that has already been allocated. Therefore, you cannot delete it, but you need to call the object's destructor.

      If you want to create an object in an already allocated memory, it won't work when you use new. In other words, placement new allows you to construct a new object in an already allocated memory (stack or heap). The void* p in the prototype is actually the first address that points to an already allocated memory buffer.

Reasons for the existence of Placement new

1. Using placement new to solve the problem of buffer

Problem Description: When you allocate an array buffer with new, the execution is inefficient because the default constructor is called. If there is no default constructor, a compile-time error occurs. If you want to create an object on pre-allocated memory, it won't work with the default new operator. To solve this problem, you can use the placement new construct. It allows you to construct a new object onto the pre-allocated memory .

2. Increasing the time-space efficiency problem

allocating memory using the new operator requires finding enough free space in the heap, which is obviously slow, and there is the possibility of an exception (not enough space) to allocate memory. Placement new can solve this problem. We construct objects in a pre-prepared memory buffer, do not need to find memory, memory allocation time is constant, and do not appear in the middle of the program run out of memory exceptions. Therefore, placement new is ideal for applications that do not want to be interrupted for long periods of time.

Placement New Use steps

In many cases, the use of placement new differs from other common new. This provides the steps to use it.

First step cache advance allocation

There are three ways of doing this:

1. In order to ensure that the memory alignment of the buffers used by placement new are properly prepared, the normal new is used to allocate it: allocate on the heap

class Task ;char * buff = new [sizeof(Task)]; //分配内存

(Note that auto or static memory is not all correctly arranged for each object type, so you will not be able to use them with placement new.) )

2. Allocating on the stack

class Task ;char buf[N*sizeof(Task)]; //分配内存

3. There is also a way to use the address directly. (Must be a meaningful address)

void* buf = reinterpret_cast<void*> (0xF00F);

Second step: Assignment of objects

In the buffer just allocated, call placement new to construct an object.

Task *ptask = new (buf) Task

Step Three: Use

Use assigned objects in the normal way:

ptask->memberfunction();ptask-> member;//...

Fourth step: object's destruction

Once you have finished using this object, you must call its destructor to destroy it. Call the destructor in the following way:

ptask->~Task(); //调用重载的析构函数

Fifth Step: Release

You can reuse the cache and assign it a new object (Repeat step 2,3,4) If you're not going to use this cache again, you can release it like this:delete [] buf;

Skipping any step can lead to run-time crashes, memory leaks, and other unexpected situations. If you do need to use placement new, follow these steps carefully.

#include <iostream>using namespace std;class X{public:    X() { cout<<"constructor of X"<<endl; }    ~X() { cout<<"destructor of X"<<endl;}    void SetNum(int n)    {        num = n;    }    int GetNum()    {        return num;    }private:    int num;};int main(){    char* buf = new char[sizeof(X)];    X *px = new(buf) X;    px->SetNum(10);    cout<<px->GetNum()<<endl;    px->~X();    delete []buf;    return 0;}

New, operator new and placement New in C + +

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.