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

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

问题描述

背景:

PIMPL成语< a>(IMPLementation的指针)是一个实现隐藏的技术,其中一个公共类包装一个结构或类,这个结构或类在公共类是其一部分的库外面是不可见的。

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类上而不是public class

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?

为了说明,这个代码将的类实现方法编译成库,

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

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

Why not implement Purr directly on the public class?

// 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 的私有成员。 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天全站免登陆