<QtClassHelperMacros>

類幫手宏。 更多...

頭: #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 )

詳細描述

宏文檔編製

Q_DISABLE_COPY ( Class )

禁用拷貝構造函數和賦值運算符的使用為給定 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 .

Q_DISABLE_COPY_MOVE ( Class )

方便宏禁用拷貝構造函數、賦值運算符、移動構造函數及移動賦值運算符的使用為給定 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 .