Explicit ctor/dtor calls

  • Thread starter Jacques Labuschagne
  • Start date
J

Jacques Labuschagne

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);
}
 
J

John Harrison

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);
}

Seems OK to me. There are a few issues here but none that you've raised in
your example code.

john
 
J

Janusz Szpilewski

Jacques 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);
}

Yes, it is legal. Such a case is described in the C++ standard (3.8/7).
The name of the object and any pointers or references to it still remain
valid after such an operation.
 
M

Michael Kochetkov

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top