I put one local variable through two object life cycles:
class Thing
{
int i;
public:
Thing() : i(44) {}
~Thing() { i = 0; }
void set(int i) { this->i = i; }
void report() const { std::cout << i << std::endl; }
};
...
Thing thing;
thing.report();
thing.set(72);
thing.report();
thing.~Thing();
new (&thing) Thing();
thing.report();
thing.set(97);
thing.report();
thing.~Thing();
thing.report();
I supposedly expect this to print the following:
44
72
44
97
0
And so it is.
But is this code guaranteed to work like that? Or does it cause undefined behavior or some of these? (I am especially suspicious of the last call report(), I just threw this out of curiosity.)
And what if a thing is a member:
struct Owner
{
Thing thing;
void go()
{
thing.report();
thing.~Thing();
new (&thing) Thing();
thing.report();
}
};
...
Owner owner;
owner.go();
Owner().go();
This also works for me. Should he?
(, , -. - , - - . , , .)