recently I have come across these two ways of creating an object in a specific place in memory:
1.
void* mem = malloc(sizeof(T));
T* obj = new(mem) T();
2.
T* obj = (T*)malloc(sizeof(T));
*obj = T();
The second way is a bit shorter…are there other differences?
Regards
Mateusz
The second way is wrong, the first is right.
You’re invoking the assignment operator on a T instance containg garbage data. The assignment operator expects the instance to have been initialized correctly – It could e.g. delete member variables before assigning, which would cause all sorts of funny crashes. See e.g:
The first way will ensure
Foo::Foo()is called – thus properly initializingData. The second way will lead to adelete Data;whereDatapoints to some random location in memory.EDIT:
You can test this the following way:
And: