Question

What's the difference between these two when we swap them? It compiles for me.

int main()
{
    X p;
    X* ptr = new (&p) X;

    X* ptr = new X (&p);
}
Was it helpful?

Solution

The line

X* ptr = new (&p) X;

uses placement new to construct a new object of type X at the location pointed at by &p. This causes undefined behavior in this particular context because p already has an object at its position (unless X is trivially copyable and destructible). It then returns a pointer to the object, which will be at the same address as p, so when we're done p and ptr will point to the same object.

The line

X* ptr = new X (&ptr);

constructs a new object of type X at a location that's dynamically allocated, passing into the constructor the value of &ptr. This only works if X has a constructor that takes in an X*. The expression then returns a pointer to the new object, which cannot be the same as &p.

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top