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);
}
1 个解决方案
#1
4
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.
使用placement new在&p指向的位置构造一个X类型的新对象。这会在此特定上下文中导致未定义的行为,因为p在其位置已经有一个对象(除非X可以轻易地复制和破坏)。然后它返回一个指向该对象的指针,该指针将与p处于同一地址,因此当我们完成时,p和ptr将指向同一个对象。
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
.
在一个动态分配的位置构造一个X类型的新对象,并将构造函数传递给&ptr。这只适用于X有一个接收X *的构造函数。然后表达式返回一个指向新对象的指针,该指针不能与&p相同。
Hope this helps!
希望这可以帮助!
#1
4
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.
使用placement new在&p指向的位置构造一个X类型的新对象。这会在此特定上下文中导致未定义的行为,因为p在其位置已经有一个对象(除非X可以轻易地复制和破坏)。然后它返回一个指向该对象的指针,该指针将与p处于同一地址,因此当我们完成时,p和ptr将指向同一个对象。
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
.
在一个动态分配的位置构造一个X类型的新对象,并将构造函数传递给&ptr。这只适用于X有一个接收X *的构造函数。然后表达式返回一个指向新对象的指针,该指针不能与&p相同。
Hope this helps!
希望这可以帮助!