继承的成本是多少? [英] What is the cost of inheritance?

查看:131
本文介绍了继承的成本是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个很基本的问题,但我仍然不确定:

This is a pretty basic question but I'm still unsure:

如果我有一个类将被实例化数百万次 - 是不是从其他类派生它?换句话说,继承是否承担一些我在实践中应该担心的成本(在构建或销毁对象的内存或运行时)?

If I have a class that will be instantiated millions of times -- is it advisable not to derive it from some other class? In other words, does inheritance carry some cost (in terms of memory or runtime to construct or destroy an object) that I should be worrying about in practice?

示例:

class Foo : public FooBase { // should I avoid deriving from FooBase?
 // ...
};

int main() {
  // constructs millions of Foo objects...
}


推荐答案

继承类在运行时不需要任何东西。

Inheriting from a class costs nothing at runtime.

类实例将如果你在基类中有变量,那么它将占用更多的内存,但是如果它们直接在派生类中,并且你没有继承任何东西,那么它将占用更多的内存。

The class instances will of course take up more memory if you have variables in the base class, but no more than if they were in the derived class directly and you didn't inherit from anything.

这不考虑 virtual 方法,这会产生小的运行时成本。

This does not take into account virtual methods, which do incur a small runtime cost.

tl; dr:You不应该担心。

tl;dr: You shouldn't be worrying about it.

这篇关于继承的成本是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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