隐式使用析构函数

Implicit use of destructor

本文关键字:析构函数      更新时间:2023-10-16

我有一个类有一个已删除的析构函数(在实践中,它需要外部帮助才能被销毁):

struct indestructible {
    indestructible(indestructible&&);
    ~indestructible() = delete;
};

当我尝试使用它的move构造函数时,编译器会抱怨:

struct user {
   indestructible ind;
   user(indestructible&& ind) : ind(std::move(ind)) {}
};
indestructible.cc:11:3: error: attempt to use a deleted function
user(indestructible&& ind) : ind(std::move(ind)) {}
^
indestructible.cc:6:3: note: '~indestructible' has been explicitly marked  deleted here
    ~indestructible() = delete;

怎么回事?没有其他成员可以抛出,构造函数主体也不能抛出,那么为什么move构造函数会调用析构函数呢?

user对象超出范围时,它将被销毁。它的成员被破坏,包括indestructible成员,这是不可能的,因为它的析构函数被删除了。

[class.base.init]/12:

在非委托构造函数中,每个直接或虚拟基类和类类型的每个非静态数据成员可能被调用(12.4)。[注意:此条款确保如果抛出异常(15.2)。--尾注]

[class.dtor]/11:

如果可能被调用的析构函数是已从调用的上下文中删除或无法访问。

对于不抛出的构造函数,没有任何例外。另见CWG 1915。