Calling the destructor + placement new

Besides being just generally frightening, does this program contain any undefined, implementation-defined, or unspecified behavior? Or is it well defined?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

template<typename T>
struct Wrapper
{
	T &t;
	Wrapper(T &t)
	: t(t)
	{
	}
	void rebind(T &t)
	{
		this->~Wrapper();
		new (this) Wrapper(t);
	}
};

int main()
{
	int x = 7, y = 4;
	Wrapper<int> w = x;
	std::cout << x << " " << y << std::endl;
	w.t = 2;
	std::cout << x << " " << y << std::endl;
	w.rebind(y);
	std::cout << x << " " << y << std::endl;
	w.t = 14;
	std::cout << x << " " << y << std::endl;
}





















7 4

2 4

2 4

2 14
http://ideone.com/Jfd3nx | http://coliru.stacked-crooked.com/a/58e0d0fe018b436e
Undefined behavior per 3.8[basic.life]/7

the name of the original object .. can be used to manipulate the new object if ... the type of the original object does not contain any non-static data members whose type is .. a reference type

(but there are cases where new (this) Whatever; is well-defined)
Last edited on
Ah, I thought there might be a man behind the curtains with references involved. Thanks, Cubbi!
@Cubbi. I read the C++ standard (2011-04-11) document. I am not getting why this case (class having reference type data member) is undefined, according to standard. Please explain. I checked this program with HP-UX g++ 4.7.0, HP-UX aCC and few online compilers like coliru, ideone.com. All of them give the same output as shown by L B.
Because
It is unspecified whether or not a reference requires storage (8.3.2/4)
Thanks JLBorges.

For the benefit others to understand
"It is unspecified whether or not a reference requires storage (8.3.2/4)"
attaching few links which talks about this:

http://www.cplusplus.com/forum/general/79527/
http://stackoverflow.com/a/14799717
Topic archived. No new replies allowed.