Topic: explicit destructor call for class member


Author: kahlke@hops.ctron (Michael J Kahlke)
Date: 10 May 1993 19:26:52 GMT
Raw View
In article 1156@mulga.cs.mu.OZ.AU, fjh@munta.cs.mu.OZ.AU (Fergus James HENDERSON) writes:
:Is the following code legal?
:
: #include <new.h>
:
: // a class with a constructor and destructor
: struct X {
:  X();
:  ~X();
:  // ...
: };
:
: struct Y {
:  X x;
:  void foo() {
:   x.~X();  // destroy member object
:   new (&x) X(); // reconstruct it
:  }
: };
:
: int main() {
:  Y y;
:  y.foo();
: }
:
:I presume that it is, since there must be some reason why
:the language supports explicit calls to class destructors.
:But I would just like to be sure :-)
:
:--
:Fergus Henderson                     This .signature virus might be
:fjh@munta.cs.mu.OZ.AU                getting old, but you still can't
:                                     consistently believe it unless you
:Linux: Choice of a GNU Generation    copy it to your own .signature file!

Yes, it *is* legal.  Section 3.7 pages 79-82 in James Coplien's "Advanced C++
Programming Styles and Idioms" deals with the issue of separation of initialization
and instantiation.  Calling the destructor explicitly causes premature cleanup of
the object.  However, storage associated with the object still exists and one can
use placement new, as you have, to re-initialize the storage with another unrelated
object of type X.  Coplien also warns against using operator delete on an object
allocated in this way.  The memory manager will be confused into thinking that the
object came from the heap instead of from the stack.

     Mike





Author: fjh@munta.cs.mu.OZ.AU (Fergus James HENDERSON)
Date: Sun, 9 May 1993 04:08:45 GMT
Raw View
Is the following code legal?

 #include <new.h>

 // a class with a constructor and destructor
 struct X {
  X();
  ~X();
  // ...
 };

 struct Y {
  X x;
  void foo() {
   x.~X();  // destroy member object
   new (&x) X(); // reconstruct it
  }
 };

 int main() {
  Y y;
  y.foo();
 }

I presume that it is, since there must be some reason why
the language supports explicit calls to class destructors.
But I would just like to be sure :-)

--
Fergus Henderson                     This .signature virus might be
fjh@munta.cs.mu.OZ.AU                getting old, but you still can't
                                     consistently believe it unless you
Linux: Choice of a GNU Generation    copy it to your own .signature file!