0

I know that we need placement new operator when memory for an object is to be allocated at a specfic memory location. e.g.

int* MemoryBuffer = malloc(sizeof(int)*10);
MyClass* Object = new (MemoryBufer) Myclass;

Can't we simply do like this

MyClass* Object = reinterpret_cast<MyClass*>(MemoryBuffer);

Object will point to the memory allocated by malloc above. Why do we need placement new operator, does it do the same thing or there is any difference?

arved
  • 4,401
  • 4
  • 30
  • 53
Akshat
  • 91
  • 8

2 Answers2

2

If you write:

    auto MemoryBuffer1 = malloc(sizeof(Myclass)); 
    Myclass *pObject1 = new (MemoryBuffer1) Myclass;

    auto MemoryBuffer2 = malloc(sizeof(Myclass));
    Myclass *pObject2 = reinterpret_cast<Myclass*>(MemoryBuffer2);

Then *pObject1 is a properly constructed object, and the constructor will have been called. *pObject2 is just a pointer to a random collection of bytes, and is not a valid object.

0

The first one (placement new) calls constructor of MyClass and second one (reinterpret cast) doesn't.

zoska
  • 1,684
  • 11
  • 23