What is the following code doing?
int a;
int *b;
b = new (&a) int(5);
is it equivalent to:
int a;
int *b;
a = 5;
b = new int(a);
?
They are NOT equivalent. The second one allocates memory and constructs an object of the given type in that memory, then returns the address of that memory. In your example, that address is stored in b
.
The first variant is called placement new and assumes that storage has already been allocated at the address pointed to by the parameter (&a
in your case) and will then construct an object of the given type at that address. It will return &a
. Also, to destruct an object constructed by placement new, the destructor must manually be called.
So the first variant allocates memory and constructs an object, whereas the second only constructs an object in previously allocated memory.
See here for details: https://en.cppreference.com/w/cpp/language/new