【发布时间】:2021-09-05 17:16:22
【问题描述】:
#define Q_DISABLE_COPY(Class) \
Class(const Class &) = delete;\
Class &operator=(const Class &) = delete;
Q_DISABLE_COPY 是 used in the QObject class,但 the documentation for it 表示它也应该在其所有子类中使用:
当您创建自己的QObject(直接或间接)子类时,您应该不给它一个复制构造函数或赋值运算符。然而,仅仅从你的类中省略它们可能是不够的,因为如果你错误地编写了一些需要复制构造函数或赋值运算符的代码(这很容易做到),你的编译器会为你精心创建它。你必须做得更多。
但是考虑一下这个程序:
struct Base {
Base() = default;
private:
Base(const Base &) = delete;
Base &operator=(const Base &) = delete;
};
struct Derived : Base {};
int main() {
Derived d1;
Derived d2(d1); // error: call to implicitly-deleted copy constructor of 'Derived'
Derived d3;
d3 = d1; // error: object of type 'Derived' cannot be assigned because its copy assignment operator is implicitly deleted
}
试图编译该程序的错误似乎表明,当在基类中删除派生类时,编译器不会在派生类中创建复制构造函数或赋值运算符。 Qt 的文档在这方面是错误的,还是在创建它们时存在一些极端情况?
相关但不重复:Repeating Q_DISABLE_COPY in QObject derived classes。它给出了在类中使用Q_DISABLE_COPY 可能有用的原因,即使它无论如何都不可复制,但并不能确认没有它它实际上永远不可复制。
【问题讨论】:
标签: c++ copy-constructor derived-class copy-assignment deleted-functions