<QtClassHelperMacros> Proxy Page

Macros

Macro Documentation

Q_DISABLE_COPY(Class)

Disables the use of copy constructors and assignment operators for the given Class.

Instances of subclasses of QObject should not be thought of as values that can be copied or assigned, but as unique identities. This means that when you create your own subclass of QObject (director or indirect), you should not give it a copy constructor or an assignment operator. However, it may not enough to simply omit them from your class, because, if you mistakenly write some code that requires a copy constructor or an assignment operator (it's easy to do), your compiler will thoughtfully create it for you. You must do more.

The curious user will have seen that the Qt classes derived from QObject typically include this macro in a private section:

class MyClass : public QObject
{
private:
    Q_DISABLE_COPY(MyClass)
};

It declares a copy constructor and an assignment operator in the private section, so that if you use them by mistake, the compiler will report an error.

class MyClass : public QObject
{
private:
    MyClass(const MyClass &) = delete;
    MyClass &operator=(const MyClass &) = delete;
};

But even this might not catch absolutely every case. You might be tempted to do something like this:

First of all, don't do that. Most compilers will generate code that uses the copy constructor, so the privacy violation error will be reported, but your C++ compiler is not required to generate code for this statement in a specific way. It could generate code using neither the copy constructor nor the assignment operator we made private. In that case, no error would be reported, but your application would probably crash when you called a member function of w.

See also Q_DISABLE_COPY_MOVE.

Q_DISABLE_COPY_MOVE(Class)

A convenience macro that disables the use of copy constructors, assignment operators, move constructors and move assignment operators for the given Class.

See also Q_DISABLE_COPY.

© 2024 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.