【发布时间】:2017-12-03 13:46:16
【问题描述】:
我有一个带有已删除析构函数的类(实际上,它需要外部帮助才能被销毁):
struct indestructible {
indestructible(indestructible&&);
~indestructible() = delete;
};
当我尝试使用它的移动构造函数时,编译器会报错:
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;
发生了什么事?没有其他成员可以抛出,构造函数体也没有,那么为什么移动构造函数会调用析构函数呢?
【问题讨论】:
-
如果
indestructible不能被破坏,那么任何包含它的对象怎么会被破坏? -
请注意,
user的析构函数仍会尝试破坏ind -
一个(稍微)比删除的析构函数更好的解决方案可能是受保护的或私有的析构函数,并且用户必须派生或成为朋友。或者,您可以设计对象,使其实际上可以具有正常的析构函数,并在构造函数中完成特殊工作
-
用户将通过类似于 std::unique_ptr
; 的方式被销毁user_destroyer::operator() 将执行清理 user 和 indestructible 所需的操作。 -
我想避免使用私有析构函数,因为我不希望它在任何情况下都被调用——没有外部信息真的没有办法摧毁 indestructible。