为什么对象“被破坏”了两次?

时间:2014-07-25 18:09:56

标签: c++ destructor

在下面的代码中,a的析构函数被调用两次,第一次调用似乎被忽略了:

struct A1
{
    int A;
    A1(int a=0) : A(a) { std::cout << "ctor: " << A << "\n"; std::cout.flush(); }
    ~A1() { std::cout << "dtor: " << A << "\n"; std::cout.flush(); }
};


int main()
{
    A1 a(1), *pa=new A1(2), *pb=new A1(3);

    a.~A1();
    pa->~A1();
    delete pb;
    std::cout << "'destructed' a.A = " << a.A << "\n"; std::cout.flush();

    return 0;
}

输出:

ctor: 1
ctor: 2
ctor: 3
dtor: 1
dtor: 2
dtor: 3
'destructed' a.A = 1
dtor: 1

这里发生了什么?

1 个答案:

答案 0 :(得分:10)

除非你真的知道自己在做什么,否则你永远不应该直接调用对象的析构函数。相反,允许在delete对象(使用new分配)或超出范围时调用析构函数。

在您的情况下,a.~A1();会导致未定义的行为,因为当a超出范围时,您将再次调用析构函数。