删除类内部

Unk*_*337 0 c++ class delete-operator

我遇到了一些奇怪的问题。我在类方法内部使用删除运算符,我想知道如何解决这个问题。

这是代码:

#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();

}
Run Code Online (Sandbox Code Playgroud)

如何检查数据是否被删除操作员删除?有可能吗?

Mat*_*son 5

  1. 使用delete this;几乎总是“坏”的。也有例外,但那些确实不寻常。想想你想做什么。大多数时候,这意味着您应该有一个包装器对象和一个由包装器对象创建/删除的内部对象。

  2. 您无法检查某些内容是否已被删除(以可靠的方式/便携的方式)。在您的特定测试用例中,您通过“在对象被销毁后使用对象”来执行“未定义的行为”,这意味着您无法真正判断会发生什么。您必须相信 C++ 运行时会按照delete标签上的说明执行操作。