类帮手宏。 更多...
| 头: |
#include <QtClassHelperMacros>
|
| Q_DISABLE_COPY ( Class ) | |
| Q_DISABLE_COPY_MOVE ( Class ) | |
(从 6.9 起)
|
Q_DISABLE_COPY_MOVE_X ( Class , reason ) |
(从 6.9 起)
|
Q_DISABLE_COPY_X ( Class , reason ) |
禁用拷贝构造函数和赋值运算符的使用为给定 Class .
实例化的子类 QObject 不应被认为是可以拷贝 (或赋值) 的值,而是作为唯一标识。这意味着当创建自己的子类化 QObject (直接或间接),应 not 赋予它拷贝构造函数 (或赋值运算符)。不管怎样,从类中简单省略它们可能不够,因为,若过失编写了一些要求拷贝构造函数 (或赋值运算符) 的代码 (这很容易做到),编译器会体贴地为您创建它。您必须做更多。
好奇用户将看到 Qt 类派生自 QObject 通常包括此宏在私有区间:
class MyClass : public QObject { private: Q_DISABLE_COPY(MyClass) };
在私有区间声明拷贝构造函数和赋值运算符,所以,若过失使用了它们,编译器会报错。
class MyClass : public QObject { private: MyClass(const MyClass &) = delete; MyClass &operator=(const MyClass &) = delete; };
即使这样,也绝对不可能捕获每种情况。可能被诱惑做像这样的一些事:
QWidget w = QWidget();
首先,不要这样做。大多数编译器将生成使用拷贝构造函数的代码,所以会报告违反隐私错误,但不要求 C++ 编译器以特定方式为该语句生成代码。可以生成代码使用
neither
拷贝构造函数
nor
私有赋值运算符。这种情况不会报错,但应用程序可能崩溃当调用成员函数从
w
.
另请参阅 Q_DISABLE_COPY_MOVE and Q_DISABLE_COPY_X .
方便宏禁用拷贝构造函数、赋值运算符、移动构造函数及移动赋值运算符的使用为给定 Class .
另请参阅 Q_DISABLE_COPY and Q_DISABLE_COPY_MOVE_X .
[since 6.9]
Q_DISABLE_COPY_MOVE_X
(
Class
,
reason
)
像 Q_DISABLE_COPY_MOVE , this macro disables copy and move operations for the class Class .
In addition, this documents the reason why this class does not support copy/move operations. In C++26 this will cause the compiler to report that reason in its error message against any code that attempts these unsupported operations.
This macro was introduced in Qt 6.9.
另请参阅 Q_DISABLE_COPY_X and Q_DECL_EQ_DELETE_X .
[since 6.9]
Q_DISABLE_COPY_X
(
Class
,
reason
)
像 Q_DISABLE_COPY , this macro disables copy operations for the class Class .
In addition, this documents the reason why this class does not support copy operations. In C++26 this will cause the compiler to report that reason in its error message against any code that attempts these unsupported operations.
This macro was introduced in Qt 6.9.
另请参阅 Q_DISABLE_COPY , Q_DISABLE_COPY_MOVE_X ,和 Q_DECL_EQ_DELETE_X .