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(示例)
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.
间接访问的用法是运行时多态接口的基础,但是分配/释放方面的代价不是(那只是常见的情况)。我们可以使用基类作为某些派生类对象的接口。当动态分配被禁止(例如在硬实时系统中)时,或者为某些插件提供稳定接口是就是这么做的。
译者注:间接访问应该指的是使用父类指针访问子类对象的情况。
???
原文链接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c10-prefer-concrete-types-over-class-hierarchies
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
有任何疑问,欢迎留言提问或讨论。
面向对象开发,面向对象思考!