Pimpl 习惯用法与纯虚拟类接口 [英] Pimpl idiom vs Pure virtual class interface

查看:44
本文介绍了Pimpl 习惯用法与纯虚拟类接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是什么让程序员选择 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.

另一方面,纯虚拟类带有用于继承实现的隐式间接(vtable),我知道没有对象创建开销.
编辑:但是如果您从外部创建对象,则需要一个工厂

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++类的时候,要考虑好要不要

When writing a C++ class, it's appropriate to think about whether it's going to be

  1. 值类型

按值复制,身份从不重要.它适合作为 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 来实现值类型(类型 1),并且只有在我真正想要最小化耦合和编译时依赖的时候才使用.通常,这不值得麻烦.正如您正确指出的那样,存在更多的语法开销,因为您必须为所有公共方法编写转发方法.对于类型 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 习惯用法与纯虚拟类接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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