Search code examples
c++classdelete-operator

Delete inside of class


I got some weird problem. I use delete operator inside of class method and I want to know how solve this problem.

This is code:

#include <iostream>

using namespace std;

class A
{
    public:
        int a;

        ~A() {
            cout << "call ~A()" << endl;
        }

        void action()
        {
            /* code here */
            delete this; //this line depends on some if statements
            /* code here */
        }

        void test2() {
            cout << "call test2()" <<  a << endl;
        }

        void test() {
            a = 10;
            cout << "call test()" << endl;

            action();

            //how can I check if data is deleted?
            test2();
        }
};

int main()
{

    A* a = new A();
    a->test();

}

How can I check if data is deleted by delete operator? Is it even possible?


Solution

    1. Using delete this; is nearly always "bad". There are exceptions, but those are really unusual. Think about what you are trying to do. Most of the time, this means that you should have a wrapper object and an inner object that is created/deleted by the wrapper object.

    2. You can't check if something has been deleted (in a reliable way/portable way). In your particular test-case, you are exercising "undefined behaviour" by "using an object after it has been destroyed", which means you can't really tell what is going to happen. You have to trust the C++ runtime that delete does what it says on the label.