There is such code:
#include <iostream>
int main()
{
int a;
int* p = new (&a) int(2);
std::cout << a << std::endl;
// delete p; error BLOCK TYPE IS INVALID
std::cin.get();
return 0;
}
The output is:
2
Why is it possible to dynamically allocate memory on stack? (I thought that heap is the right place to do this). And, why does delete operator return error in this case, but new operator work?
This is called placement-new. It doesn’t allocate memory. It constructs the object in the same memory of
a. In placement new, it’s the user who specifies the memory region wherenewoperator constructs the object. In your code above, you specify the memory region by writing(&a)expression just after thenewkeyword. Since&ais not a dynamically allocated memory, you cannotdeleteit:It would give runtime error, it attempts to delete the memory where the variable
aresides.However, if you dynamically allocate the memory, then you can do delete it. Lets suppose,
Ais some class, then you should be doing this:This is simplest example of placement-new which explains the syntax only. But the story doesn’t end here; it is the beginning and to make it work properly, the memory pointed to by
bufferhas to be aligned properly for the object type, and in the above example, I simply assumed so. In the real code, you cannot make such dangerous assumption. Now read this FAQ: