Using placement new to update a reference member?

£可爱£侵袭症+ 提交于 2019-12-01 09:26:24

This is perfectly invalid.

[basic.life]/1, emphasis mine:

The lifetime of an object of type T ends when:

  • if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
  • the storage which the object occupies is reused or released.

The placement new reuses the storage, ending the lifetime of the object denoted by f.

[basic.life]/7:

If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if:

  • the storage for the new object exactly overlays the storage location which the original object occupied, and
  • the new object is of the same type as the original object (ignoring the top-level cv-qualifiers), and
  • the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type, and
  • the original object was a most derived object (1.8) of type T and the new object is a most derived object of type T (that is, they are not base class subobjects).

Since the third bullet point is not satisfied, after a call to Bar, f does not refer to the object created by the placement new, but to the no-longer-living object previously there, and attempting to use it results in undefined behavior.

See also CWG1776 and P0137R0.

It may be legal, but it's incredibly poor style. The argument to placement new is a void*, so you're telling C++ to reinterpret_cast the address of f as a void*, then using that as the location to construct something new - overwriting the original f.

Basically, don't do that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!