简体   繁体   中英

What's the difference between these two new syntaxes?

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);
}

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM