Is the following code legal in C++?
template<typename T>
class Foo {
public:
Foo(T& v) : v_(v) {}
private:
T& v_;
};
int a = 10;
Foo<int> f(a);
void Bar(int& a) {
new (&f)Foo<int>(a);
}
References are not supposed to be bound twice, right?
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.