我有一个删除了析构函数的类(实际上,它需要外部帮助才能被销毁):
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)
这是怎么回事?没有其他成员可以抛出,构造函数体也没有,那么为什么移动构造函数调用析构函数有什么原因呢?
当您的user对象超出范围时,它将被破坏.它的成员被破坏,包括indestructible成员,这是不可能的,因为它的析构函数被删除了.
\n\n\n\n\n在非委托构造函数中,可能会调用每个直接或虚拟基类以及类类型的每个非静态数据成员的析构函数 (12.4)。[注意:此规定确保在抛出异常时可以为完全构造的子对象调用析构函数 (15.2)。\xe2\x80\x94尾注]
\n
\n\n\n如果可能调用的析构函数被删除或无法从调用上下文访问,则程序是格式错误的。
\n
不抛出异常的构造函数也不例外。另请参见CWG 1915。
\n