turn from: http://www.cnblogs.com/younes/archive/2010/04/26/1721528.html
First we distinguish the next few confusing keywords:
New (also known as new operator), operator new, placement new. Look at the following code:
The new here is the first of the three keywords mentioned above and becomes the new operator. In fact, it performs the following 3 processes:
1. Call operator new to allocate memory
2. Call constructor to generate class object
3. Return the corresponding pointer
Placement new is a standard, global version of the overloaded operator new. It cannot be replaced by a custom version (unlike the normal operator new and operator delete can be replaced with a user-defined version). Its prototype is as follows:?
1 |
void *operator new (size_t, void *p) throw () {return p;} |
The new and delete operators should all be used, which is to request and release the memory in the heap, both of which cannot be overloaded. To implement different memory allocation behaviors, you need to overload the operator new and operator deletes, rather than new and delete.
operator new, like operator+, can be overloaded. However, it is not possible to overload the prototype for void operator new (size_t size) globally, which is typically only overloaded in the class. If there is no overload operator new 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.
As for placement new, it's just an overloaded version of operator new, but we rarely use it. If you want to create an object in the allocated memory, it won't work when you use new. In other words, placement new allows you to construct an object in an already allocated memory (stack or heap). The void*p in the prototype is actually the first address that points to a allocated memory buffer.
We know that using the new operator to allocate memory requires looking for enough space in the heap, which is slow, and it is possible to have an exception that cannot allocate memory (not enough space). Placement new can solve this problem. We construct objects in a prepared memory buffer, do not need to find memory, memory allocation time is constant. And it does not appear to run out of memory in the middle of the program. Therefore, placement new is ideal for applications that have high time requirements and do not want to be interrupted for long periods of time. Placement new uses the following method:
1. Buffer allocation in advance, you can use the heap space, you can also use the stack space. So there are two ways to distribute:?
1 2 3 |
Class MyClass {...}; Char *buf= new char [n sizeof (MyClass) + sizeof (int)]; |