Search code examples
c++explicit-destructor-call

Access member variables after destructor call


i have code like this:

class Foo {
  public:
    void blub () {}
};
class Test {
  public:
  Foo& foo;
  Test (Foo& f) : foo (f) {}
  void test () {
    this->~Test ();
    foo.blub ();
  }
};

After the explicit call to the destructor, all member variables of my Test class are probably inaccessible, so the call foo.blub() is invalid. If I store the reference in a local variable to avoid access to the member variable, is the call to foo.blub() guaranteed to work? Can't the compiler optimize the local variable out and access the member variable after the destructor call, making it invalid again?

class Foo {
  public:
    void blub () {}
};
class Test {
  public:
  Foo& foo;
  Test (Foo& f) : foo (f) {}
  void test () {
    Foo& f = foo;
    this->~Test ();
    f.blub ();
  }
};

Solution

  • Your local f refers to an object outside of Test and f will persist as long as test() does, so yes it will work.