Jacques Labuschagne said:
Hi all,
Is it legal to kill an object and build a new one of the same type in its
memory?
class A{
int i;
public:
explicit A(int value): i(value){}
};
int main(){
A a(3);
a.~A();
new (&a)A(2);
}
Let us suppose the first constructor succeeds and the second fails with the
exception (it is not your case indeed but let us debate in general). A
compiler must call the destructor for the successfully created a(3) local
variable when it leaves the scope and he knows that the construction was
successful. But your unsuccessful placement new really confuses it and, I
believe, you may expect crashes, because if the second construction throws
no destructor shall be called but it would be called for a(3).
So, IMO, your solution may appear to be dangerous in general and I would
recommend you to use the traditional approach of using a buffer of proper
amount of chars with the subsequent placement new if you are interested in
the final result.