Construct an Object on a Pre-Allocated char Array

The memory buffer returned by operator new is guaranteed to have the suitable alignment properties for any type object. This property enables you to construct objects on such a pre-allocated char array. For example:

 #include #include #include using namespace std;class Employee{ /*...*/};void f(){    char * pc = new char[sizeof(Employee)];  Employee *pemp = new (pc) Employee;  //construct on properly aligned char array  //...use pemp  pemp->Employee::~Employee(); //explicit destruction  delete [] pc;} 
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: