3

Can i still access an object after making an explicit call to its destructor?

for example,

class A{
        public:
            A(){
                cout<<"Constructor\n";
                x=5;
            }
            ~A(){
                cout<<"Destructor\n";
            }
        int x;
    };


int main() {
    ios_base::sync_with_stdio(false);

    A obj;
    obj.~A();
    obj.x=4;
    cout<<obj.x<<endl;

    return 0;
}

gives output

Constructor Destructor 4 Destructor

How am I able to access obj.x even after calling the destructor? If the explicit call does not destroy the object, then what does it do?

grv95
  • 33
  • 2

1 Answers1

0

It calls the destructor, but it doesn't deallocate the memory. Memory will be deallocated at the end of the function.

BTW, if you don't understand what happens, you probably shouldn't do that: the destructor will be called a second time at the end of the scope, which may cause issues if it can't be called twice (which is often the case).

Arkanosis
  • 2,229
  • 1
  • 12
  • 18