本文介绍了如何使用Qt的PIMPL成语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 Qt自己的类实现通过使用PIMPL成语将接口与实现干净分离。然而,Qt提供的机制没有记录。如何使用它们? 我想这是Qt中关于我如何PIMPL的规范问题。 当我们有半复杂实现的任何东西时,使用PIMPL的动机变得显而易见。进一步的动机在。 接口 现在我们将解释基于PIMPL的 c $ c $ class in the interface(header)file。 Q_DECLARE_PRIVATE宏 Q_DECLARE_PRIVATE 宏必须放在类声明的 private 部分。它将接口类的名称作为参数。它声明了 d_func()助手方法的两个内联实现。该方法返回具有适当的const const的PIMPL指针。当在const方法中使用时,它返回指向 const PIMPL的指针。在非const方法中,它返回一个指向非const PIMPL的指针。它还在派生类中提供了一个正确类型的pimpl。因此,从实现内部对pimpl的所有访问都是使用 d_func()和**不通过 d_ptr 。通常我们使用 Q_D 宏,如下面的实现部分所述。 宏有两种口味: Q_DECLARE_PRIVATE(Class)//假定PIMPL指针名为d_ptr Q_DECLARE_PRIVATE(Dptr,Class)/ /显式地使用PIMPL指针名称 在我们的例子中, Q_DECLARE_PRIAVATE(CoordinateDialog) 相当于 Q_DECLARE_PRIVATE(d_ptr,CoordinateDialog)。 Q_PRIVATE_SLOT宏 此宏仅用于Qt 4兼容性或针对非C ++ 11编译器。对于Qt 5,C ++ 11代码,它是没有必要的,因为我们可以连接函子到信号,并且没有必要显式的私人插槽。 我们有时需要一个 QObject 具有内部使用的专用插槽。这样的插槽会污染接口的私有部分。因为有关槽的信息只与moc代码生成器相关,所以我们可以使用 Q_PRIVATE_SLOT 宏告诉moc要通过 d_func()指针,而不是通过 this 。 moc在 Q_PRIVATE_SLOT 中预期的语法是: Q_PRIVATE_SLOT ,方法签名) 在我们的例子中: Q_PRIVATE_SLOT(d_func(),void onAccepted()) 这有效地在 CoordinateDialog 类上声明了一个 onAccepted 插槽。 moc生成以下代码以调用槽: d_func() - > onAccepted() 宏本身有一个空扩展 - 它只提供给moc的信息。 我们的界面类扩展如下: class CoordinateDialog:public QDialog { Q_OBJECT / *我们不扩展它在这里,因为它的主题。 * / // Q_DECLARE_PRIVATE(CoordinateDialog) inline CoordinateDialogPrivate * d_func(){ return reinterpret_cast< CoordinateDialogPrivate *>(qGetPtrHelper(d_ptr)); } inline const CoordinateDialogPrivate * d_func()const { return reinterpret_cast< const CoordinateDialogPrivate *>(qGetPtrHelper(d_ptr)); } friend class CoordinateDialogPrivate; // Q_PRIVATE_SLOT(d_func(),void onAccepted()) //(空) QScopedPointer< CoordinateDialogPrivate> const d_ptr; public: [...] }; 使用此宏时,必须将moc生成的代码包含在私有类完全定义。在我们的示例中,这意味着 CoordinateDialog.cpp 文件应结束: #includemoc_CoordinateDialog.cpp Gotchas 要在类声明中使用的所有 Q _ 宏包括分号。在 Q _ 后不需要显式分号: verbose,有双分号 class Foo:public QObject {class Foo:public QObject { Q_OBJECT Q_OBJECT; Q_DECLARE_PRIVATE(...)Q_DECLARE_PRIVATE(...); ... ... }; }; PIMPL 不能 c $ c> Foo 本身: //正确//错误 class FooPrivate ; class Foo { class Foo {class FooPrivate; ... ... }; }; 类声明中的大括号后的第一部分是默认的私有。因此,以下是等价的: //不太冗长,优先//详细 class Foo {class Foo { int privateMember; private: int privateMember; }; }; Q_DECLARE_PRIVATE 类的名称,而不是PIMPL的名称: //正确//错误 class Foo {class Foo { Q_DECLARE_PRIVATE(Foo)Q_DECLARE_PRIVATE(FooPrivate) ... ... }; }; PIMPL指针应该对于不可复制/ code> QObject 。 由于PIMPL是内部实现细节,所以它的大小在接口所在的站点不可用用过的。使用placement new和 Fast Pimpl 习语的诱惑应该被抵制,因为它不会为任何类别提供任何好处 实施 必须在实施文件中定义PIMPL。如果它很大,也可以在私有头中定义,通常名为 foo_p.h 的接口在 foo.h 。 PIMPL至少只是主类数据的载体。它只需要一个构造函数,没有其他方法。在我们的例子中,它还需要存储指向主类的指针,因为我们想从主类发射一个信号。因此: // CordinateDialog.cpp #include< QFormLayout> #include< QDoubleSpinBox> #include< QDialogBu​​ttonBox> class CoordinateDialogPrivate { Q_DISABLE_COPY(CoordinateDialogPrivate) Q_DECLARE_PUBLIC(CoordinateDialog) CoordinateDialog * const q_ptr; QFormLayout布局; QDoubleSpinBox x,y,z; QDialogBu​​ttonBox按钮; QVector3D坐标; void onAccepted(); CoordinateDialogPrivate(CoordinateDialog *); }; PIMPL不可复制。由于我们使用不可复制的成员,任何复制或分配给PIMPL的尝试都将被编译器捕获。通常,最好使用 Q_DISABLE_COPY 明确禁用复制功能。 Q_DECLARE_PUBLIC 宏的工作方式类似于 Q_DECLARE_PRIVATE 。 我们将对话框的指针传递给构造函数,允许我们在对话框中初始化布局。我们还将 QDialog 的接受信号连接到内部 onAccepted 插槽。 CoordinateDialogPrivate :: CoordinateDialogPrivate(CoordinateDialog * dialog): q_ptr(dialog),布局(dialog),按钮(QDialogBu​​ttonBox :: Ok | QDialogBu​​ttonBox :: Cancel) { layout.addRow(X,& x); layout.addRow(Y,& y); layout.addRow(Z,& z); layout.addRow(& buttons); dialog-> connect(& buttons,SIGNAL(accepted()),SLOT(accept())); dialog-> connect(& buttons,SIGNAL(rejected(rejected),SLOT(reject())); #if QT_VERSION< = QT_VERSION_CHECK(5,0,0) this-> connect(dialog,SIGNAL(accepted()),SLOT(onAccepted #else QObject :: connect(dialog,& QDialog :: accepted,[this] {onAccepted();}); #endif } onAccepted PIMPL方法需要在Qt 4 /非C ++ 11项目中作为插槽公开。对于Qt 5和C ++ 11,这不再是必要的。 接受对话框后,我们捕获坐标并发出 acceptedCoordinates 信号。这就是为什么我们需要公共指针: void CoordinateDialogPrivate :: onAccepted(){ Q_Q(CoordinateDialog); coordinates.setX(x.value()); coordinates.setY(y.value()); coordinates.setZ(z.value()); emit q-> acceptedCoordinates(coordinates); } Q_Q 宏声明一个局部 CoordinateDialog * const q 变量。 实现的公共部分构造了PIMPL并显示其属性: CoordinateDialog :: CoordinateDialog(QWidget * parent,Qt :: WindowFlags flags): QDialog(parent,flags), d_ptr(new CoordinateDialogPrivate {} QVector3D CoordinateDialog :: coordinates()const { Q_D(const CoordinateDialog); return d-> coordinates; } CoordinateDialog ::〜CoordinateDialog(){} Q_D 宏声明了一个局部 CoordinateDialogPrivate * const d 变量。 Q_D宏 要在接口中访问PIMPL 方法,我们可以使用 Q_D 宏,传递它的接口类的名称。 void Class :: foo()/ * non-const * / { Q_D(Class); / *需要一个分号! * / //展开为 ClassPrivate * const d = d_func(); ... 要在 const接口中访问PIMPL 方法,我们需要在 const 关键字前面添加类名: void Class :: bar()const { Q_D(const Class); //展开为 const ClassPrivate * const d = d_func(); ... Q_Q宏 要从非const PIMPL 方法访问接口实例,我们可以使用 Q_Q 宏,接口类。 void ClassPrivate :: foo()/ * non-const * / { Q_Q ; / *需要一个分号! * / //展开为 Class * const q = q_func(); ... 要访问接口实例 const PIMPL 方法,我们用 const 关键字作为类名的前缀,就像我们对 Q_D 宏: / p> void ClassPrivate :: foo()const { Q_Q(const Class); / *需要一个分号! * / // expand to const Class * const q = q_func(); ... Q_DECLARE_PUBLIC宏 此宏是可选的,用于允许从PIMPL访问接口。如果PIMPL的方法需要操纵接口的基类或发出其信号,则通常使用它。等效的 Q_DECLARE_PRIVATE 宏用于允许从界面访问 PIMPL 。 宏将接口类的名称作为参数。它声明了 q_func()助手方法的两个内联实现。该方法返回具有适当constness的接口指针。当在const方法中使用时,它返回一个指向 const 接口的指针。在非const方法中,它返回一个指向非const接口的指针。它还在派生类中提供正确类型的接口。接下来,使用 q_func()和**不通过 q_ptr 。通常我们使用上面描述的 Q_Q 宏。 宏期望接口的指针是命名为 q_ptr 。没有这个宏的双参数变体,它允许为接口指针选择一个不同的名称(如 Q_DECLARE_PRIVATE )。 宏扩展如下: class CoordinateDialogPrivate { // Q_DECLARE_PUBLIC CoordinateDialog) inline CoordinateDialog * q_func(){ return static_cast< CoordinateDialog *>(q_ptr); } inline const CoordinateDialog * q_func()const { return static_cast< const CoordinateDialog *>(q_ptr); } friend class CoordinateDialog; // CoordinateDialog * const q_ptr; ... }; Q_DISABLE_COPY宏 复制构造函数和赋值运算符。 常见问题 给定类的接口头必须是实现文件中包含的第一个头。这迫使标题是自包含的,而不依赖于恰好包含在实现中的声明。如果不是这样,实现将无法编译,允许您修复界面以使其自给自足。 // correct // error prone // Foo.cpp // Foo.cpp #includeFoo.h#include< SomethingElse> #include< SomethingElse> #includeFoo.h //现在Foo.h可以依赖于SomethingElse而没有 //我们知道这个事实。 必须出现 Q_DISABLE_COPY 巨集在PIMPL的私人部分 //正确//错误 // Foo.cpp // Foo。 cpp class FooPrivate {class FooPrivate { Q_DISABLE_COPY(FooPrivate)public: ... Q_DISABLE_COPY(FooPrivate)}; ... }; PIMPL和非QObject可复制类 PIMPL成语允许实现可复制,复制和移动可构造的可分配对象。该任务通过复制和交换方式完成,防止代码复制。当然,PIMPL指针不能是const。 在C ++ 11中,我们需要注意四分法,并提供以下内容的全部:复制构造函数,移动构造函数,赋值运算符和析构函数。和自由的 swap 函数来实现它,当然†。 接口 / Integer.h #include< algorithm> class IntegerPrivate; class Integer { Q_DECLARE_PRIVATE(Integer) QScopedPointer< IntegerPrivate> d_ptr; public: Integer(); Integer(int); Integer(const Integer& other); Integer(Integer&& other); operator int&(); operator int()const; Integer& operator =(Integer other); friend void swap(Integer& first,Integer& second)/ * nothrow * /; 〜Integer(); }; 对于性能,move构造函数和赋值运算符应在接口他们不需要直接访问PIMPL: Integer :: Integer(Integer&& other):Integer ){ swap(* this,other); } 整数& Integer :: operator =(Integer other){ swap(* this,other); return * this; } 所有这些都使用 swap 独立的函数,我们必须在界面中定义。请注意,这是 void swap(Integer& first,Integer& second)/ * nothrow * / { using std :: swap; swap(first.d_ptr,second.d_ptr); } 实施 这是相当直接。我们不需要从PIMPL访问接口,因此 Q_DECLARE_PUBLIC 和 q_ptr 不存在。 // Integer.cpp class IntegerPrivate { public: int value; IntegerPrivate(int i):value(i){} }; Integer :: Integer():d_ptr(new IntegerPrivate(0)){} Integer :: Integer(int i):d_ptr(new IntegerPrivate(i)){} Integer :: Integer(const Integer& other): d_ptr(new IntegerPrivate(other.d_func() - > value)){} Integer :: operator int& d_func() - > value; } Integer :: operator int()const {return d_func() - > value; } Integer ::〜Integer(){} http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom\">这个出色的回答:还有其他声称我们应该专注 std :: swap 为我们的类型,提供一个交换旁边的自由功能交换等,但是这是不必要的:任何正确使用 swap 将通过非限定调用,我们的函数将通过ADL 。一个函数会做。 Qt's own class implementations cleanly separate out the interfaces from the implementations through the use of the PIMPL idiom. Yet, the mechanisms provided by Qt are undocumented. How to use them?I'd like this to be the canonical question about "how do I PIMPL" in Qt. The answers are to be motivated by a simple coordinate entry dialog interface shown below.The motivation for the use of PIMPL becomes apparent when we have anything with a semi-complex implementation. Further motivation is given in this question. Even a fairly simple class has to pull in a lot of other headers in its interface.The PIMPL-based interface is fairly clean and readable. // CoordinateDialog.h#include <QDialog>#include <QVector3D>class CoordinateDialogPrivate;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 &);};Q_DECLARE_METATYPE(QVector3D)A Qt 5, C++11 based interface doesn't need the Q_PRIVATE_SLOT line.Compare that to a non-PIMPL interface that tucks implementation details into the private section of the interface. Note how much other code has to be included.// CoordinateDialog.h#include <QDialog>#include <QVector3D>#include <QFormLayout>#include <QDoubleSpinBox>#include <QDialogButtonBox>class CoordinateDialog : public QDialog{ QFormLayout m_layout; QDoubleSpinBox m_x, m_y, m_z; QVector3D m_coordinates; QDialogButtonBox m_buttons; Q_SLOT void onAccepted();public: CoordinateDialog(QWidget * parent = 0, Qt::WindowFlags flags = 0); QVector3D coordinates() const; Q_SIGNAL void acceptedCoordinates(const QVector3D &);};Q_DECLARE_METATYPE(QVector3D)Those two interfaces are exactly equivalent as far as their public interface is concerned. They have the same signals, slots and public methods. 解决方案 IntroductionThe PIMPL is a private class that contains all of the implementation-specific data of the parent class. Qt provides a PIMPL framework and a set of conventions that need to be followed when using that framework. Qt's PIMPLs can be used in all classes, even those not derived from QObject.The PIMPL needs to be allocated on the heap. In idiomatic C++, we must not manage such storage manually, but use a smart pointer. Either QScopedPointer or std::unique_ptr work for this purpose. Thus, a minimal pimpl-based interface, not derived from QObject, might look like:// Foo.h#include <QScopedPointer>class FooPrivate; ///< The PIMPL class for Fooclass Foo { QScopedPointer<FooPrivate> const d_ptr;public: Foo(); ~Foo();};The destructor's declaration is necessary, since the scoped pointer's destructor needs to destruct an instance of the PIMPL. The destructor must be generated in the implementation file, where the FooPrivate class lives:// Foo.cppclass FooPrivate { };Foo::Foo() : d_ptr(new FooPrivate) {}Foo::~Foo() {}See also:A deeper exposition of the idiom.Gotchas and pitfalls of PIMPL.The InterfaceWe'll now explain the PIMPL-based CoordinateDialog interface in the question.Qt provides several macros and implementation helpers that reduce the drudgery of PIMPLs. The implementation expects us to follow these rules:The PIMPL for a class Foo is named FooPrivate.The PIMPL is forward-declared along the declaration of the Foo class in the interface (header) file.The Q_DECLARE_PRIVATE MacroThe Q_DECLARE_PRIVATE macro must be put in the private section of the class's declaration. It takes the interface class's name as a parameter. It declares two inline implementations of the d_func() helper method. That method returns the PIMPL pointer with proper constness. When used in const methods, it returns a pointer to a const PIMPL. In non-const methods, it returns a pointer to a non-const PIMPL. It also provides a pimpl of correct type in derived classes. It follows that all access to the pimpl from within the implementation is to be done using d_func() and **not through d_ptr. Usually we'd use the Q_D macro, described in the Implementation section below.The macro comes in two flavors:Q_DECLARE_PRIVATE(Class) // assumes that the PIMPL pointer is named d_ptrQ_DECLARE_PRIVATE(Dptr, Class) // takes the PIMPL pointer name explicitlyIn our case, Q_DECLARE_PRIAVATE(CoordinateDialog) is equivalent to Q_DECLARE_PRIVATE(d_ptr, CoordinateDialog).The Q_PRIVATE_SLOT MacroThis macro is only needed for Qt 4 compatibility, or when targeting non-C++11 compilers. For Qt 5, C++11 code, it is unnecessary, as we can connect functors to signals and there's no need for explicit private slots.We sometimes need for a QObject to have private slots for internal use. Such slots would pollute the interface's private section. Since the information about slots is only relevant to the moc code generator, we can, instead, use the Q_PRIVATE_SLOT macro to tell moc that a given slot is to be invoked through the d_func() pointer, instead of through this.The syntax expected by moc in the Q_PRIVATE_SLOT is:Q_PRIVATE_SLOT(instance_pointer, method signature)In our case:Q_PRIVATE_SLOT(d_func(), void onAccepted())This effectively declares an onAccepted slot on the CoordinateDialog class. The moc generates the following code to invoke the slot:d_func()->onAccepted()The macro itself has an empty expansion - it only provides information to moc.Our interface class is thus expanded as follows:class CoordinateDialog : public QDialog{ Q_OBJECT /* We don't expand it here as it's off-topic. */ // Q_DECLARE_PRIVATE(CoordinateDialog) inline CoordinateDialogPrivate* d_func() { return reinterpret_cast<CoordinateDialogPrivate *>(qGetPtrHelper(d_ptr)); } inline const CoordinateDialogPrivate* d_func() const { return reinterpret_cast<const CoordinateDialogPrivate *>(qGetPtrHelper(d_ptr)); } friend class CoordinateDialogPrivate; // Q_PRIVATE_SLOT(d_func(), void onAccepted()) // (empty) QScopedPointer<CoordinateDialogPrivate> const d_ptr;public: [...]};When using this macro, you must include the moc-generated code in a place where the private class is fully defined. In our case, this means that the CoordinateDialog.cpp file should end with:#include "moc_CoordinateDialog.cpp"GotchasAll of the Q_ macros that are to be used in a class declaration already include a semicolon. No explicit semicolons are needed after Q_:// correct // verbose, has double semicolonsclass Foo : public QObject { class Foo : public QObject { Q_OBJECT Q_OBJECT; Q_DECLARE_PRIVATE(...) Q_DECLARE_PRIVATE(...); ... ...}; };The PIMPL must not be a private class within Foo itself:// correct // wrongclass FooPrivate; class Foo {class Foo { class FooPrivate; ... ...}; };The first section after the opening brace in a class declaration is private by default. Thus the following are equivalent:// less wordy, preferred // verboseclass Foo { class Foo { int privateMember; private: int privateMember;}; };The Q_DECLARE_PRIVATE expects the interface class's name, not the PIMPL's name:// correct // wrongclass Foo { class Foo { Q_DECLARE_PRIVATE(Foo) Q_DECLARE_PRIVATE(FooPrivate) ... ...}; };The PIMPL pointer should be const for non-copyable/non-assignable classes such as QObject. It can be non-const when implementing copyable classes.Since the PIMPL is an internal implementation detail, its size is not available at the site where the interface is used. The temptation to use placement new and the Fast Pimpl idiom should be resisted as it provides no benefits for anything but a class that doesn't allocate memory at all.The ImplementationThe PIMPL has to be defined in the implementation file. If it is large, it can also be defined in a private header, customarily named foo_p.h for a class whose interface is in foo.h.The PIMPL, at a minimum, is merely a carrier of the main class's data. It only needs a constructor and no other methods. In our case, it also needs to store the pointer to the main class, as we'll want to emit a signal from the main class. Thus:// CordinateDialog.cpp#include <QFormLayout>#include <QDoubleSpinBox>#include <QDialogButtonBox>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*);};The PIMPL is not copyable. Since we use non-copyable members, any attempt to copy or assign to the PIMPL would be caught by the compiler. Generally, it's best to explicitly disable the copy functionality by using Q_DISABLE_COPY.The Q_DECLARE_PUBLIC macro works similarly to Q_DECLARE_PRIVATE. It is described later in this section.We pass the pointer to the dialog into the constructor, allowing us to initialize the layout on the dialog. We also connect the QDialog's accepted signal to the internal onAccepted slot.CoordinateDialogPrivate::CoordinateDialogPrivate(CoordinateDialog * dialog) : q_ptr(dialog), layout(dialog), buttons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel){ layout.addRow("X", &x); layout.addRow("Y", &y); layout.addRow("Z", &z); layout.addRow(&buttons); dialog->connect(&buttons, SIGNAL(accepted()), SLOT(accept())); dialog->connect(&buttons, SIGNAL(rejected()), SLOT(reject()));#if QT_VERSION <= QT_VERSION_CHECK(5,0,0) this->connect(dialog, SIGNAL(accepted()), SLOT(onAccepted()));#else QObject::connect(dialog, &QDialog::accepted, [this]{ onAccepted(); });#endif}The onAccepted() PIMPL method needs to be exposed as a slot in Qt 4/non-C++11 projects. For Qt 5 and C++11, this is no longer necessary.Upon the acceptance of the dialog, we capture the coordinates and emit the acceptedCoordinates signal. That's why we need the public pointer:void CoordinateDialogPrivate::onAccepted() { Q_Q(CoordinateDialog); coordinates.setX(x.value()); coordinates.setY(y.value()); coordinates.setZ(z.value()); emit q->acceptedCoordinates(coordinates);}The Q_Q macro declares a local CoordinateDialog * const q variable. It is described later in this section.The public part of the implementation constructs the PIMPL and exposes its properties:CoordinateDialog::CoordinateDialog(QWidget * parent, Qt::WindowFlags flags) : QDialog(parent, flags), d_ptr(new CoordinateDialogPrivate(this)){}QVector3D CoordinateDialog::coordinates() const { Q_D(const CoordinateDialog); return d->coordinates;}CoordinateDialog::~CoordinateDialog() {}The Q_D macro declares a local CoordinateDialogPrivate * const d variable. It is described below.The Q_D MacroTo access the PIMPL in an interface method, we can use the Q_D macro, passing it the name of the interface class.void Class::foo() /* non-const */ { Q_D(Class); /* needs a semicolon! */ // expands to ClassPrivate * const d = d_func(); ...To access the PIMPL in a const interface method, we need to prepend the class name with the const keyword:void Class::bar() const { Q_D(const Class); // expands to const ClassPrivate * const d = d_func(); ...The Q_Q MacroTo access the interface instance from a non-const PIMPL method, we can use the Q_Q macro, passing it the name of the interface class.void ClassPrivate::foo() /* non-const*/ { Q_Q(Class); /* needs a semicolon! */ // expands to Class * const q = q_func(); ...To access the interface instance in a const PIMPL method, we prepend the class name with the const keyword, just as we did for the Q_D macro:void ClassPrivate::foo() const { Q_Q(const Class); /* needs a semicolon! */ // expands to const Class * const q = q_func(); ...The Q_DECLARE_PUBLIC MacroThis macro is optional and is used to allow access to the interface from the PIMPL. It is typically used if the PIMPL's methods need to manipulate the interface's base class, or emit its signals. The equivalent Q_DECLARE_PRIVATE macro was used to allow access to the PIMPL from the interface.The macro takes the interface class's name as a parameter. It declares two inline implementations of the q_func() helper method. That method returns the interface pointer with proper constness. When used in const methods, it returns a pointer to a const interface. In non-const methods, it returns a pointer to a non-const interface. It also provides the interface of correct type in derived classes. It follows that all access to the interface from within the PIMPL is to be done using q_func() and **not through q_ptr. Usually we'd use the Q_Q macro, described above.The macro expects the pointer to the interface to be named q_ptr. There is no two-argument variant of this macro that would allow to choose a different name for the interface pointer (as was the case for Q_DECLARE_PRIVATE).The macro expands as follows:class CoordinateDialogPrivate { //Q_DECLARE_PUBLIC(CoordinateDialog) inline CoordinateDialog* q_func() { return static_cast<CoordinateDialog*>(q_ptr); } inline const CoordinateDialog* q_func() const { return static_cast<const CoordinateDialog*>(q_ptr); } friend class CoordinateDialog; // CoordinateDialog * const q_ptr; ...};The Q_DISABLE_COPY MacroThis macro deletes the copy constructor and the assignment operator. It must appear in the private section of the PIMPL.Common GotchasThe interface header for a given class must be the first header to be included in the implementation file. This forces the header to be self-contained and not dependent on declarations that happen to be included in the implementation. If it isn't so, the implementation will fail to compile, allowing you to fix the interface to make it self-sufficient.// correct // error prone// Foo.cpp // Foo.cpp#include "Foo.h" #include <SomethingElse>#include <SomethingElse> #include "Foo.h" // Now "Foo.h" can depend on SomethingElse without // us being aware of the fact.The Q_DISABLE_COPY macro must appear in the private section of the PIMPL// correct // wrong// Foo.cpp // Foo.cppclass FooPrivate { class FooPrivate { Q_DISABLE_COPY(FooPrivate) public: ... Q_DISABLE_COPY(FooPrivate)}; ... };PIMPL And Non-QObject Copyable ClassesThe PIMPL idiom allows one to implement copyable, copy- and move- constructible, assignable object. The assignment is done through the copy-and-swap idiom, preventing code duplication. The PIMPL pointer must not be const, of course.Recall the in C++11, we need to heed the Rule of Four, and provide all of the following: the copy constructor, move constructor, assignment operator, and destructor. And the free-standing swap function to implement it all, of course†.We'll illustrate this using a rather useless, but nevertheless correct example.Interface// Integer.h#include <algorithm>class IntegerPrivate;class Integer { Q_DECLARE_PRIVATE(Integer) QScopedPointer<IntegerPrivate> d_ptr;public: Integer(); Integer(int); Integer(const Integer & other); Integer(Integer && other); operator int&(); operator int() const; Integer & operator=(Integer other); friend void swap(Integer& first, Integer& second) /* nothrow */; ~Integer();};For performance, the move constructor and the assignment operator should be defined in the interface (header) file. They don't need to access the PIMPL directly:Integer::Integer(Integer && other) : Integer() { swap(*this, other);}Integer & Integer::operator=(Integer other) { swap(*this, other); return *this;}All of those use the swap freestanding function, which we must define in the interface as well. Note that it is void swap(Integer& first, Integer& second) /* nothrow */ { using std::swap; swap(first.d_ptr, second.d_ptr);}ImplementationThis is rather straightforward. We don't need access to the interface from the PIMPL, thus Q_DECLARE_PUBLIC and q_ptr are absent.// Integer.cppclass IntegerPrivate {public: int value; IntegerPrivate(int i) : value(i) {}};Integer::Integer() : d_ptr(new IntegerPrivate(0)) {}Integer::Integer(int i) : d_ptr(new IntegerPrivate(i)) {}Integer::Integer(const Integer &other) : d_ptr(new IntegerPrivate(other.d_func()->value)) {}Integer::operator int&() { return d_func()->value; }Integer::operator int() const { return d_func()->value; }Integer::~Integer() {}†Per this excellent answer: There are other claims that we should specialize std::swap for our type, provide an in-class swap along-side a free-function swap, etc. But this is all unnecessary: any proper use of swap will be through an unqualified call, and our function will be found through ADL. One function will do. 这篇关于如何使用Qt的PIMPL成语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 20:15