【发布时间】:2020-05-16 15:29:17
【问题描述】:
我有一个只能移动的 Base 类和一个继承 Base 构造函数的 Derived。我想给 Derived 一个自定义析构函数,但是当我这样做时,它不再继承 Base 的移动构造函数。很神秘。发生了什么?
// move-only
struct Base {
Base() = default;
Base(Base const &) = delete;
Base(Base &&) {}
};
struct Derived : public Base {
using Base::Base;
// remove this and it all works
~Derived() { /* ... */ }
};
int main() {
Base b;
// works
Base b2 = std::move(b);
Derived d;
// fails
Derived d2 = std::move(d);
}
【问题讨论】:
-
也许给
Derived一个移动构造函数?如果 Derived 有任何数据成员,则基本移动构造函数将不正确 -
您的基类没有虚拟析构函数。不确定这是否是问题所在,但似乎很可疑。
标签: c++ inheritance destructor move-semantics