为什么要“PIMPL"习惯用法? [英] Why should the "PIMPL" idiom be used?

查看:42
本文介绍了为什么要“PIMPL"习惯用法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:

PIMPL Idiom(指向实现的指针)是一种实现隐藏的技术,其中公共类包装了在公共类所属的库之外无法看到的结构或类.

The PIMPL Idiom (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of.

这对库的用户隐藏了内部实现细节和数据.

This hides internal implementation details and data from the user of the library.

在实现这个习惯用法时,为什么要将公共方法放在 pimpl 类而不是公共类上,因为公共类方法的实现会被编译到库中,而用户只有头文件?

When implementing this idiom why would you place the public methods on the pimpl class and not the public class since the public classes method implementations would be compiled into the library and the user only has the header file?

为了举例说明,这段代码将 Purr() 实现放在 impl 类上并对其进行了包装.

To illustrate, this code puts the Purr() implementation on the impl class and wraps it as well.

为什么不直接在公共类上实现 Purr?

// header file:
class Cat {
    private:
        class CatImpl;  // Not defined here
        CatImpl *cat_;  // Handle

    public:
        Cat();            // Constructor
        ~Cat();           // Destructor
        // Other operations...
        Purr();
};


// CPP file:
#include "cat.h"

class Cat::CatImpl {
    Purr();
...     // The actual implementation can be anything
};

Cat::Cat() {
    cat_ = new CatImpl;
}

Cat::~Cat() {
    delete cat_;
}

Cat::Purr(){ cat_->Purr(); }
CatImpl::Purr(){
   printf("purrrrrr");
}

推荐答案

  • 因为您希望 Purr() 能够使用 CatImpl 的私有成员.如果没有 friend 声明,Cat::Purr() 将不允许这样的访问.
  • 因为你不会混合职责:一类实现,一类转发.
    • Because you want Purr() to be able to use private members of CatImpl. Cat::Purr() would not be allowed such an access without a friend declaration.
    • Because you then don't mix responsibilities: one class implements, one class forwards.
    • 这篇关于为什么要“PIMPL"习惯用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆