前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.10:具体类型要好于类继承

C++核心准则C.10:具体类型要好于类继承

作者头像
面向对象思考
发布2020-03-25 15:55:14
4150
发布2020-03-25 15:55:14
举报

C.10: Prefer concrete types over class hierarchies

C.10:具体类型要好于类继承

译者注:具体类型的定义请参照大师本人作品《C++程序设计语言》第四版的16.3节。还可以参考以下两个网页:

1.https://softwareengineering.stackexchange.com/questions/221437/concrete-types-as-described-by-stroustrup-c-programming-language-4th-ed

2.https://stackoverflow.com/questions/25853450/their-representation-is-part-of-their-definition-as-related-to-c-concrete-type

Reason(原因)

A concrete type is fundamentally simpler than a hierarchy:easier to design, easier to implement, easier to use, easier to reason about, smaller, and faster.You need a reason (use cases) for using a hierarchy.

具体类型基本上会比继承类型简单:容易设计,容易实现,容易使用,容易定义用途,而且占有更小的空间,具有更快的速度。使用继承是需要理由(用例)。

Example(示例)

代码语言:javascript
复制
class Point1 {
    int x, y;
    // ... operations ...
    // ... no virtual functions ...
};

class Point2 {
    int x, y;
    // ... operations, some virtual ...
    virtual ~Point2();
};

void use()
{
    Point1 p11 {1, 2};   // make an object on the stack
    Point1 p12 {p11};    // a copy

    auto p21 = make_unique<Point2>(1, 2);   // make an object on the free store
    auto p22 = p21->clone();                // make a copy
    // ...
}

If a class can be part of a hierarchy, we (in real code if not necessarily in small examples) must manipulate its objects through pointers or references. That implies more memory overhead, more allocations and deallocations, and more run-time overhead to perform the resulting indirections.

如果某类能够成为继承关系的一部分,我们(在实际开发中如果例子较小时不一定)必须通过指针或引用操作它的对象。这意味着更多的内存消耗,更多的分配和释放动作,同时也需要更多的运行时代价以执行继承带来的间接访问。

Note(注意)

Concrete types can be stack-allocated and be members of other classes.

具体类型可以在堆栈上分配而且成为其他类的成员。

Note(注意)

The use of indirection is fundamental for run-time polymorphic interfaces. The allocation/deallocation overhead is not (that's just the most common case). We can use a base class as the interface of a scoped object of a derived class. This is done where dynamic allocation is prohibited (e.g. hard-real-time) and to provide a stable interface to some kinds of plug-ins.

间接访问的用法是运行时多态接口的基础,但是分配/释放方面的代价不是(那只是常见的情况)。我们可以使用基类作为某些派生类对象的接口。当动态分配被禁止(例如在硬实时系统中)时,或者为某些插件提供稳定接口是就是这么做的。

译者注:间接访问应该指的是使用父类指针访问子类对象的情况。

Enforcement(实施建议)

???

原文链接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c10-prefer-concrete-types-over-class-hierarchies

觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

有任何疑问,欢迎留言提问或讨论。


面向对象开发,面向对象思考!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-12-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Enforcement(实施建议)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档