在派生类中定义destructor需要复制赋值操作符。

问题描述 投票:0回答:1

看看这段代码的例子。

class A {
    A(const A&) = delete;
    A &operator=(const A&) = delete;    
protected:
    A() { }
    virtual ~A() { } // required for inheritance
    A(A&&) = default;
    A &operator=(A&&) = default;
};

struct B : public A {
    ~B() { } // Without the destructor the code compiles
};

int main(void)
{
    B b = B();
}

这段代码无法编译,因为... ... g++-9 告诉我

第15行:错误:使用被删除的函数'B::B(const B&)'第9行:注意:'B::B(const B&)'被隐式删除,因为默认的定义会不规范:第9行:错误:使用被删除的函数'A::A(A&)'

参见 榫头 获取完整的错误信息。

为什么编译器不使用来自于 class A? 如果我删除了定义在 struct B 的代码编译。出现这种行为的原因是什么?

c++ destructor move-semantics
1个回答
3
投票

当你做

~B() { }

B 停止编译器生成一个移动构造函数,所以它只有一个复制构造函数。 由于 A'的是不能接受的,它不能编译。

当你删除它时,编译器可以自动创建move构造函数,你就可以了。


注意,这只适用于C++17之前。 有了C++17的保证复制洗脱。B b = B(); 成为 B b(); (如果这样真的能编译的话),所以不会发生复制或移动。

© www.soinside.com 2019 - 2024. All rights reserved.