Home >Backend Development >C++ >How to Use the Qt PIMPL Idiom in C ?
The PIMPL (Pointer to Implementation) idiom allows for separating the public interface from the private implementation details of a class, preventing users of the class from being concerned with those details. Qt employs its own implementation of the PIMPL idiom, which is documented below.
The PIMPL-based interface for Qt looks as follows:
<code class="cpp">class CoordinateDialog : public QDialog { Q_OBJECT Q_DECLARE_PRIVATE(CoordinateDialog) #if QT_VERSION <= QT_VERSION_CHECK(5,0,0) Q_PRIVATE_SLOT(d_func(), void onAccepted()) #endif QScopedPointer<CoordinateDialogPrivate> const d_ptr; public: CoordinateDialog(QWidget * parent = 0, Qt::WindowFlags flags = 0); ~CoordinateDialog(); QVector3D coordinates() const; Q_SIGNAL void acceptedCoordinates(const QVector3D &); };</code>
Here, the Q_DECLARE_PRIVATE macro declares the PIMPL class and provides the necessary mechanisms to access it.
The PIMPL class, CoordinateDialogPrivate, is defined in the implementation file:
<code class="cpp">class CoordinateDialogPrivate { Q_DISABLE_COPY(CoordinateDialogPrivate) Q_DECLARE_PUBLIC(CoordinateDialog) CoordinateDialog * const q_ptr; QFormLayout layout; QDoubleSpinBox x, y, z; QDialogButtonBox buttons; QVector3D coordinates; void onAccepted(); CoordinateDialogPrivate(CoordinateDialog*); };</code>
The Q_DECLARE_PRIVATE macro simplifies the declaration of the PIMPL class and associates it with the interface class. It generates inline implementations of the d_func() helper method, which provides access to the PIMPL with appropriate constness.
This macro is used for Qt 4 compatibility or when targeting non-C 11 compilers. It declares a private slot for internal use.
The Q_DECLARE_PUBLIC macro provides access to the interface from the PIMPL. It generates inline implementations of the q_func() helper method, similar to d_func().
The PIMPL idiom can also be used for copyable, non-QObject classes. However, the PIMPL pointer must be non-const. The Rule of Four (copy constructor, move constructor, assignment operator, destructor) and a free-standing swap function should be implemented.
The above is the detailed content of How to Use the Qt PIMPL Idiom in C ?. For more information, please follow other related articles on the PHP Chinese website!