New, operator new, and placement new

Source: Internet
Author: User
1. Native operator new

Let's start with native operator new. Consider the following code, which is used to allocate five int-type spaces and return the pointer to them [1]:

Int* V =Static_cast<Int*> (::Operator New(5 *Sizeof(* V )));

For the above call, operator new plays the native memory allocation role, similar to malloc. The above is equivalent:

Int* V =Static_cast<Int*> (Malloc (5 *Sizeof(* V )));

Release the memory allocated with operator new with operator delete:

::Operator Delete(V );

Ii. Meaning of placement new

Placement new is a standard and global version that reloads operator new. It cannot be replaced by custom versions (unlike normal versions of operator new and operator Delete can be replaced ).

Void * operator new (size_t, void * P) Throw () {return P ;}

Placement new ignores the size_t parameter and returns only the second parameter. The result is that you can place an object in a specific place to call the constructor.

Unlike other common new ones, it has another parameter in brackets. For example:
Widget * P = new widget;--// ordinary New
Pi = new (PTR) int; // placement new

The parameter PTR In the Ampersand is a pointer pointing to a memory buffer. Placement new will assign an object to the buffer. The return value of placement new is the address of the constructed object (such as the passing parameter in brackets ). Placement new is mainly applicable to: In applications with very high time requirements, because the time allocated by these programs is determined; programs that run for a long time without being interrupted; and execute a garbage collector (Garbage Collector ).

 

Iii. Differences between new, operator new and placement new

New: cannot be overloaded, and its behavior is always consistent. It first calls operator new to allocate memory, and then calls the constructor to initialize that memory.

Operator New: to implement different memory allocation behaviors, You Should reload operator new instead of new.

Delete is similar to operator Delete.

 

Delete first calls the object's destructor, and then calls operator Delete to release the memory used.

 

Placement new: it is only a version of operator new. It does not allocate memory, but returns a pointer to a memory segment that has been allocated. Therefore, you cannot delete it, but you need to call the object's destructor.

4. Execution of the new operator

(1) call operator new to allocate memory;
(2). Call the constructor to generate class objects;
(3). Return the corresponding pointer.

Operator new can be reloaded just like operator +. If operator new is not overloaded in the class, the global OPERATOR: Operator new is called to split the heap. Similarly, operator new [], operator delete, and operator Delete [] can also be overloaded. In fact, placement new is also an overloaded version of operator new, which is rarely used. If you want to create an object in the allocated memory, using new will not work. That is to say, placement new allows you to construct a new object in a allocated memory (stack or heap. In the prototype, void * P actually points to the first address of a allocated memory buffer.

5. Reasons for the existence of placement new

(1). Use placement new to solve the buffer problem.
Description: The execution efficiency is poor because the default constructor is called when the new array is used for buffering. If no default constructor is available, a compile-time error occurs. If you want to create objects in the pre-allocated memory, the default new operator will not work. To solve this problem, you can construct it using placement new. It allows you to construct a new object to the pre-allocated memory.

 

(2). Increase the Space-Time Efficiency
 
To allocate memory using the new operator, you need to find enough space in the heap. Obviously, this operation is very slow and there may be exceptions that cannot allocate memory (insufficient space ).
Placement new can solve this problem. The constructed objects are all carried out in a pre-prepared memory buffer. The memory allocation time does not need to be searched. The memory allocation time is constant, and there will be no internal memory insufficiency exceptions during the program running process. Therefore, placement new is very suitable for applications that require high time requirements and do not want to be interrupted for a long time.

 

Vi. Instances
 1 #include<stdio.h> 2  3 char* buffer[1024]; 4 class LinearAllocator 5 { 6 public: 7     void* alloc(size_t){ 8         return buffer; 9     }10 };11 12 class DisplayListOp {13 public:14     DisplayListOp(int a, int b){15         printf("a = %d  b = %d\n", a, b);16     }17 18     static void operator delete(void* ptr,int param) { 19         printf("delete param = %d\n", param);20     };21 22     static void operator delete(void* ptr) { 23         printf("delete no param \n");24     };25 26     static void* operator new(size_t size, LinearAllocator& allocator,int param) {27         printf("operator new param = %d\n", param);28         return allocator.alloc(size);29     }30 };31 32 33 34 int main()35 {36     LinearAllocator lineAlloc;37     DisplayListOp* pw = new (lineAlloc, 11) DisplayListOp(12,13);38     delete pw;39 40     return 0;41 }

 

Result

operator new param = 11a = 12  b = 13delete no param

The above example and result can be inferred.

 

 

New (linealloc, 11) displaylistop (12, 13)
In the expression above, parameters in the first bracket are not passed to the operator new function, and parameters in the second bracket are passed to the class constructor.
This overload function is used if the static void operator Delete (void * PTR) operation is performed.

 

 

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.