menu

hjk41的日志

Avatar

More Effective C++ 8: Understand different meanings of new and delete

There are new operator, operator new and placement new.

new operator

string * ps=new string("hello");


This is the new operator. The new operator is built into C++ like sizeof(), and you can never change the behavior of this operator.
new operator does two things:
(1) invoke the operator new to allocate enough space to hold the object
(2) calls the constructor to initialize the object

operator new
Operator new allocates raw memory of a given size, just like malloc() in C. It is usually declared and used like this:


void * operator new (size_t size);
void * rawMemory=operator new (sizeof(string));


We can overload operator new to customize its behavior. For example, if we are using a lot of news and deletes on instances of a class, we can create a memory pool and overload operator new and operator delete.

placement new
As memtioned above, the new operator always calls operator new to get the memory for the object. Sometimes we alread have the raw memory, and we want to place the object in the memory. In this case, we can use placement new.


void * rawMemory=operator new (sizeof(string));
string * ps=new(rawMemory) string("hello");


Here, rawMemory can have been allocated by operator new or malloc().

delete
The behavior of delete operator and operator delete is must the same as that of new opeator and operator new. However, there is no "placement delete". The reason why placement delete exists is that we can't call the constructor on an object ourselves. However, we can call the destructor, thus no need for "placement delete".


void * rawMemory=operator new(sizeof(string));  // operator new
string * ps=new(rawMemory) string("hello");   // placement new
ps->~string();  // no need for "placement delete"
operator delete(ps);  // operator delete

arrays

string * ps=new string[10];


Here, the new operator is called, but it behaves slightly differently from the one above. It will call the operator new[] instead of operator new. So if you overloads operator new and operator delete, don't forget to overload operator new[] and operator delete[].
operator new[] is quite the same as operator new:


class A{
public:
    void * operator new[](size_t size){
        if(size % sizeof(A)!=0)
            return ::operator new[](size);
        cout<<"size of the array: "<<size%sizeof(A)<<endl;
        return ::operator new[](size);
    }
};

评论已关闭