使用d指针的优点和缺点是什么

使用d指针的优点和缺点是什么

本文介绍了使用d指针的优点和缺点是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

d指针在Qt中被大量使用,它们是pimpl成语的实现。我知道pimpl成语的优点和缺点。但我错过了d指针实现的优势。 和这里是d指针的示例。
不是更容易使用这个吗?

d-pointers are heavily used in Qt, they are an implementation of pimpl idiom. I know advantages and disadvantages of pimpl idiom. But I have missed the advantages of d-pointers implementation. Here and here are the samples of d-pointers.Isn't it easier to just use this?

class MyClassPrivate;
class MyClass {
  // interface methods
private:
  MyClassPrivate *pimpl_;
};


推荐答案

d指针模式的宏集提供了一些排序方便和一致性。例如,Q_DECLARE_PRIVATE确保Foo的pimpl私有类被命名为FooPrivate,FooPrivate结束Foo,并创建一个很好的内联函数(const和nonconst版本),称为d_func()。后者用于Q_D宏,基本上创建一个指向私有类实例的作用域/局部变量d。

The set of macros for d-pointer pattern provides some sort convenience and consistencies. For example, Q_DECLARE_PRIVATE ensures that the pimpl private class for Foo is named as FooPrivate, that FooPrivate befriends Foo, and creates an nice inline function (both const and nonconst versions) called d_func(). The latter is used in Q_D macro, which basically creates a scoped/local variable d which points to the private class instance.

简而言之,您不需要使用Q_DECLARE_PRIVATE和其他宏,但这样做会使代码更短,更清晰,更一致。

In short, you need not use Q_DECLARE_PRIVATE and other macros, but doing so will make the code shorter, cleaner, and consistent.

这篇关于使用d指针的优点和缺点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!