问题描述
我想知道什么会让程序员选择Pimpl成语或纯虚拟类和继承。
I was wondering what would make a programmer to choose either Pimpl idiom or pure virtual class and inheritance.
我理解pimpl成语带有一个显式的额外间接每个公共方法和对象创建开销。
I understand that pimpl idiom comes with one explicit extra indirection for each public method and the object creation overhead.
另一方面,Pure虚拟类带有隐式间接(vtable)用于继承实现,我理解没有对象创建
EDIT :但如果您从外部创建对象,则需要一个工厂
The Pure virtual class in the other hand comes with implicit indirection(vtable) for the inheriting implementation and I understand that no object creation overhead.
EDIT: But you'd need a factory if you create the object from the outside
使得纯虚拟类比pimpl成语更不理想?
What makes the pure virtual class less desirable than the pimpl idiom?
推荐答案
在编写C ++类时,
$ b
When writing a C++ class, it's appropriate to think about whether it's going to be
-
A值类型
A Value Type
身份永远不重要。它适合作为std :: map中的键。示例,字符串类或日期类或复数类。
Copy by value, identity is never important. It's appropriate for it to be a key in a std::map. Example, a "string" class, or a "date" class, or a "complex number" class. To "copy" instances of such a class makes sense.
实体类型
重要。总是通过引用传递,从不通过值。通常,复制类的实例没有意义。当它有意义时,多态克隆方法通常更合适。示例:一个Socket类,一个Database类,一个策略类,任何将在功能语言中闭包的东西。
Identity is important. Always passed by reference, never by "value". Often, doesn't make sense to "copy" instances of the class at all. When it does make sense, a polymorphic "Clone" method is usually more appropriate. Examples: A Socket class, a Database class, a "policy" class, anything that would be a "closure" in a functional language.
pImpl和纯抽象基类都是减少编译时依赖的技术。
Both pImpl and pure abstract base class are techniques to reduce compile time dependencies.
但是,我只使用pImpl来实现Value类型),并且有时候我真的想减少耦合和编译时依赖。通常,这不值得麻烦。正如你正确地指出,有更多的语法开销,因为你必须为所有的公共方法编写转发方法。对于类型2类,我总是使用一个纯的抽象基类和相关的工厂方法。
However, I only ever use pImpl to implement Value types (type 1), and only sometimes when I really want to minimize coupling and compile-time dependencies. Often, it's not worth the bother. As you rightly point out, there's more syntactic overhead because you have to write forwarding methods for all of the public methods. For type 2 classes, I always use a pure abstract base class with associated factory method(s).
这篇关于Pimpl成语与Pure虚拟类接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!