[Revisit.SolidMCP] 更广泛使用pimpl idiom

pImpl是大规模和跨平台程序开发一大利器,Piaoger在SolidMCP中有用过,但是不常用,为每个东东都搞一个pImpl,一路调去,也挺累的。

前几日看了牛人写的一本书,详细分析了pImpl的优缺点,很有些启发:

优点:

1. Information hiding.

我们把所有的实现细节留给pImpl,在Interface class中,甚至除了pImpl指针,没有任何成员变量,也没有private的方法。

这样,Interface class就非常干净与简洁,只让第三方看到可以调用的方法。
2. Reduced coupling.

如果不是使用pImpl,在interface class声明的头文件中,难免会include一些乱七八糟的头文件,自然也就造成了耦合。

3.Faster compiles

减少了耦合,少解析了些header文件,自然编译起来也就快了。

4. 二进制兼容

这个是我们比较少注意的优势。

5. Lazy Allocation.

缺点:

1. You must now allocate and free an additional implementation object for every object that is created.

2. extra developer inconvenience to prefix all private member accesses with something like mImpl >

这就是我前面提到的体力活啦,其实也挺累人的。

3. compiler will no longer catch changes to member variables within const methods.

原文地址:https://www.cnblogs.com/piaoger/p/2103455.html