c++ - 为什么对象 'destructed' 两次?

标签 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

这里发生了什么?

最佳答案

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

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

关于c++ - 为什么对象 'destructed' 两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24961985/

相关文章:

c++ - 在插入其他线程时有效地遍历 map

c++ - 使用 Win32 C++ 访问 protected 网络共享

c++ - 有没有办法在 C++ 中使用模板函数来做到这一点

c++ - g++ __static_initialization_and_destruction_0(int, int) - 它是什么

C++ - 在基元上运行析构函数?

c++ - 使用移动构造函数时,构造函数中没有默认参数

c++ - 从 class_Type 名称访问 vector 值不允许错误

c++ - shared_ptr 魔法 :)

c++ - 析构函数末尾的段错误

c - 安全释放 XS 代码中的资源(在作用域退出时运行析构函数)