C + + new operator, delete operator, operator new, operator delete, new placement

Source: Internet
Author: User

Http://www.younfor.com/cpp-new-placement-new-operator-new.html

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

http://kelvinh.github.io/blog/2014/04/19/research-on-operator-new-and-delete/

New operator is the keyword new defined in C + +, and the behavior triggered by calling new, delete operator similar

New operator, which is a function that defines its own function assignment behavior

New Class; //  ... Delete pc;

new operator   , and the third line is   delete operator   The code is simple, But for the compiler, it needs to do extra work, translating the above code into something similar to the following:

 void  *p = operator  new  (sizeof   (Class));  //  Call the constructor of class for the memory that P points to, and there is no visual code to show  Class *pc = Static_cast<class*> (p);  //  ...  Pc->~class ();  operator  delete  (PC); 

In the above code, the first line operator new is, and the operator delete last line is , very simple and straightforward. So, actually, new operator Two things are done:

    1. Call operator new Allocate memory
    2. Initializes the object (calling the constructor) on the allocated memory, and returns a pointer to the object.

Instead delete operator , call the destructor, and then call operator delete free memory.

Let's take a look at one of the implementations of the C + + standard library--clang's libcxx is how to implement the global operator new/delete (header file declaration here, implementation here, I removed some control compilation options looking at the messy macro definition, leaving only the core code):

void*operator New(std::size_t size)Throw(std::bad_alloc) {if(Size = =0) Size=1; void*p;  while(P =::malloc(size)) ==0) {Std::new_handler nh=Std::get_new_handler (); if(NH) NH (); Else            ThrowStd::bad_alloc (); }    returnp;}void operator Delete(void*ptr) {    if(PTR):: Free(PTR);}

This code is simple, but, originally, the mysterious operator new/delete in the back is just secretly called C function library malloc/free ! This, of course, is about implementation, and Libcxx does not represent other implementations.

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

New operator
(1) Call operator new to allocate enough space and call the constructor of the related object
(2) can not be overloaded

operator NEW
(1) 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
-If there is new_handler, call New_handler, otherwise
-If no exception is required (expressed in the nothrow parameter), the BAD_ALLOC exception is executed, otherwise
--Return 0
(2) can be overloaded
(3) When overloading, the return type must be declared as void*
(4) When overloading, the first parameter type must be the size (in bytes) of the allocation space for the expression requirement, type size_t
(5) When overloading, can take other parameters

Delete is similar to delete operator

NEW:

The new operator, C + + built-in operator. cannot be overloaded, its behavior is always consistent.

The specific operation is equivalent to: Call operator new to allocate memory, then call the constructor to initialize the memory space, and then return the memory space address

operator NEW:

The new function, which can be overloaded. To implement different memory allocation behaviors, you should overload operator new instead of new.

Placement NEW:

Just one version of the operator new overload. It does not allocate memory, but returns a pointer to a memory that has already been allocated.

So when you delete the object, you only need to call the object's destructor, and you don't have to use the delete operator to free up space.

The new here is actually performing the following 3 procedures:
1. Call operator new to allocate memory;

2. Call the constructor to generate the class object;

3. Return the appropriate pointer.

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, usually one of your overloads, then finally the remaining three are overloaded again.

As for placement new is the focus of this article. In fact it's just an overloaded version of operator new, but it's rarely used. If you want to be in an already allocated memory

Creating an object that doesn'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). Prototype

Void*p is actually the first address that points to an already allocated memory buffer.

We know that allocating memory using the new operator requires finding enough free space in the heap, which is 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 does 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.

Here's how to use it:


1. Buffer Advance allocation
You can use heap space or stack space, so there are two ways to allocate it:
Class MyClass {...};
Char *buf=new char[n*sizeof (MyClass) +sizeof (int)], or char buf[n*sizeof (MyClass) +sizeof (int)];

2. Construction of objects
MyClass * Pclass=new (BUF) MyClass;

3. Destruction of objects
Once this object is used, you must explicitly call the class's destructor to destroy the object. However, the memory space is not freed so that other objects are constructed.
Pclass->~myclass ();

4. Release of Memory
If the buffer is in the heap, then call delete[] BUF; release the memory; if it is in the stack, then it is valid within its scope, and the memory is freed automatically by jumping out of scope.

Attention:

    • In the C + + standard, for placement operator new [] The following description:

Placement operator new[] needs implementation-defined amount of additional storage to save a size of array.

So we have to apply more than the size of the original object, sizeof (int) bytes to hold the number of objects, or the size of the array.

    • How to use the new in the second step is placement new, in fact, does not apply for memory, just call the constructor, return a pointer to the already allocated memory,

So when the object is destroyed, you do not need to call Delete to free space, but you must call the destructor to destroy the object.

C + + new operator, delete operator, operator new, operator delete, new placement

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.