暗中使用析构函数

Avi*_*ity 6 c++ c++11

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

struct indestructible {
    indestructible(indestructible&&);
    ~indestructible() = delete;
};
Run Code Online (Sandbox Code Playgroud)

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

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;
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?没有其他成员可以抛出,构造函数体也没有,那么为什么移动构造函数调用析构函数有什么原因呢?

Joh*_*hnB 7

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

  • 在我的示例中,用户对象永远不会超出任何范围.考虑:`auto user = new user(std :: move(*new indestructible));`所以从不调用`user`的析构函数.还要考虑编译器错误消息的上下文 - 它是`user`的移动构造函数.为什么必须在那里实例化析构函数? (2认同)

T.C*_*.C. 3

[class.base.init]/12 :

\n\n
\n

在非委托构造函数中,可能会调用每个直接或虚拟基类以及类类型的每个非静态数据成员的析构函数 (12.4)。[注意:此规定确保在抛出异常时可以为完全构造的子对象调用析构函数 (15.2)。\xe2\x80\x94尾注]

\n
\n\n

[class.dtor]/11:

\n\n
\n

如果可能调用的析构函数被删除或无法从调用上下文访问,则程序是格式错误的。

\n
\n\n

不抛出异常的构造函数也不例外。另请参见CWG 1915。

\n