C + + Placement new operator __c++

Source: Internet
Author: User


When processing memory allocations, C + + programmers use the new operator (operator new) to allocate memory and use the delete operator (operator delete) to free up memory. While this type of writing works well for most of the time, it's annoying to use new in some situations, such as when you want to construct an object on a pre-configured memory.


If you want to create an object on a pre-configured memory, it won't work with the default new operator. To solve this problem, you can use placement new constructs.
It allows you to construct a new object into the preconfigured memory:

Placement new is a standard, global version of the overloaded operator new, which cannot be replaced by a custom version (unlike normal operator new and operator delete can be replaced with a user-defined version).



Its prototype is as follows:

void *operator new (size_t, void *p) throw () {return p;}


First we distinguish the next few easy to confuse keywords: new, operator new, placement new

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 operator new instead of new and delete.


Look at the following code:

Class MyClass {};

MyClass * P=new MyClass;


The new here is actually performing the following 3 procedures:

1 call operator new to allocate memory;

2 invokes the constructor to generate the class object;

3 returns the corresponding pointer.

operator new, like operator+, can be overloaded, but it cannot be overloaded globally with a prototype of void operator new (size_t size), which can generally only be overloaded in a 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, generally you overload one of them, then it is best to overload the remaining three.

Placement New is an overloaded version of operator new, but we rarely use it. If you want to create an object in an already allocated memory, it is not possible to 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 there is no out-of-memory exception in the middle of the program run. Therefore, placement new is ideal for applications that have high time requirements and do not want to be interrupted for long periods of time.


Use the following methods:

1. Buffer Advance Allocation

You can use the heap's space:
Class MyClass {...};

Char *buf=new char[n*sizeof (MyClass) + sizeof (int)];


You can also use the stack space

Char buf[n*sizeof (MyClass) + sizeof (int)];


You can also allocate memory by malloc.
void* buf=malloc (sizeof (MyClass));

2. Construction of objects


myclass* pclass=new (BUF) MyClass;


3. Destruction of objects

Once this object is used, you must explicitly invoke the class's destructor to destroy the object. However, the memory space is not freed so that other objects are constructed.
Pclass->~myclass ();
Tips: There is actually no application memory, just call the constructor, return a pointer to the allocated memory, so the object is destroyed without calling delete free space, but the destructor must be called to destroy the object. (Learn about new constructs and destructors)


4. Release of Memory

If the buffer is in the heap, then the delete[] buf is invoked, the memory is freed, and if it is in the stack, it is active within its scope, and the memory is automatically released.



New, actually do two things, one is: Call malloc allocate the required memory, the second is: Call the constructor.

Delete, but also do two things, one is: Invoke the destructor, the second is: Call free freed memory.

and placement new memory is allocated in advance, we create objects when the object is placed in the memory allocated in advance.


The test code is as follows:

#include <iostream> #include <stdlib.h> #define N using namespace std;

int g_id = 0;
		Class MyClass {Public:myclass () {id_ = ++g_id;
		name_ = "Default";
	cout << "Default constructors" << Endl;
		} MyClass (string name) {name_ = name;
	cout << "constructors" << Endl;
	} ~myclass () {cout << "destructors:id =" << id_ << ", name =" << name_ << Endl;
	} Private:int id_;

String name_;

};
	int main () {myclass* pmyclass = new MyClass ("MM");

	Delete Pmyclass;
	Char *buf = new char[sizeof (MyClass)];
	MyClass *pclass = new (BUF) MyClass ("Mjf1");

	Pclass->~myclass ();
	MyClass *pclass2 = new (BUF) MyClass ("Mjf2");

	Pclass2->~myclass ();
	void* buf2=malloc (sizeof (MyClass));
	MyClass *PCLASS3 = new (BUF) MyClass ("mjf3");

	Pclass3->~myclass ();
	Char *buf3 = new Char[sizeof (MyClass) * N];

	MyClass *pclass4 = new (BUF3) myclass[n];
			for (int i=0 i < N; ++i) {//pclass4[i].~myclass (); (PclasS4+i)->~myclass ();
return 0;

 }




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.