Placement new Layout New Operation

Source: Internet
Author: User

Placement new is to use someone else to allocate the memory, and then another variable or object will directly occupy this.

It is equivalent to a house built by someone, but the last thing to live in is another person, which is similar to the idiom "Chao Jiu Zhan.

The above buffer1 and buffer2 have allocated the memory (the house has been built) in the memory, but the following two statements are 20 and 21,

Just like a bandit, directly live in the room. In the result box, we can see P2. P4 memory is in the memory of buffer1 and buffer2 (in the House ).

That is to say, it is not allocated in the heap, but "occupied" in the global variable (So delete is not needed here ).

Why placement new?


(1). Use placement new to solve the buffer problem.

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 and do not need to be searched for memory. The memory allocation time is constant;

It does not cause internal memory insufficiency during the program running. Therefore, placement new is very suitable for applications that require high time requirements and do not want to be interrupted for a long time.

========================================================== ========================================================

The following is an example of someone else's article:

Http://www.cnblogs.com/wanghetao/archive/2011/11/21/2257403.html

Placement new (transfer) about placement new

Author: hzh512
1. 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 mainly applies:

In applications with very high requirements on time, 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 ).

2. 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.

3. 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, operator 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 an allocated memory buffer.

4. Reasons for the existence of placement new

(1). Use placement new to solve the buffer problem.
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 and do not need to be searched for memory. The memory allocation time is constant;

It does not cause internal memory insufficiency during the program running. Therefore, placement new is very suitable for applications that require high time requirements and do not want to be interrupted for a long time.

5. Procedure

In many cases, the use of placement new is different from that of other common new ones. The procedure is provided here.

Step 1 cache allocation in advance

There are three methods:

1. To ensure that memory alignmen (memory Queue) in the cache area used by placement new is correctly prepared, use normal New to allocate it: allocate on the stack
Class task;
Char * buff = new [sizeof (task)]; // allocate memory
(Note that auto or static memory is not correctly arranged for each object type. Therefore, you cannot use them with placement new .)
2. Allocate on Stack
Class task;
Char Buf [N * sizeof (task)]; // allocate memory
3. Another method is to use the address directly. (Must be a meaningful address)
Void * Buf = reinterpret_cast <void *> (0xf00f );

Step 2: allocate objects
Call placement new in the allocated cache area to construct an object.
Task * ptask = new (BUF) task

Step 3: Use

Use the allocated object in the normal way:
Ptask-> memberfunction ();
Ptask-> member;
//...

Step 4: analyze the object structure

Once you use this object, you must call its destructor to destroy it. Call the Destructor as follows:
Ptask-> ~ Task (); // call external destructor

Step 5: Release
You can reuse the cache repeatedly and assign it a new object (Repeat steps 2, 3, 4). If you do not intend to use the cache again, you can release it like this:
Delete [] Buf;
Skipping any step may cause the running time to crash, memory leakage, and other unexpected situations. If you do need placement new, follow these steps carefully.

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.