在C ++中继承的运行时成本(没有虚拟)? [英] Runtime cost of inheritance (without virtuality) in C++?

查看:105
本文介绍了在C ++中继承的运行时成本(没有虚拟)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用-O3编译的C ++中,没有虚拟化的继承会产生以下成本:

In C++ compiled with -O3, does inheritance without virtuality have a cost in terms of :


  • 执行时间

  • 记忆

如果答案是肯定的:为什么?

If the answer is yes : why ?

例如:MyClass1和MyClass2在性能和内存方面是否等同?

As an example : are MyClass1 and MyClass2 equivalent in terms of performance and memory ?

推荐答案


p>

execution time

什么?函数是静态解析的,因此函数调用是相同的。 MyClass1 的构造函数将调用基类的构造函数,其析构函数将调用基类的析构函数,因此构造函数破坏可能会有一些开销。 可能。有些编译器可能会优化调用。

Of what? Functions are resolved statically, so function calls are the same. MyClass1's constructor will call the constructors of base classes, and its destructor will call destructors of base classes, so for construction & destruction there may be some overhead. Maybe. Some compilers might optimize the calls away.


内存

memory


$ b b

这将是相同的,只有一个成员 double 。理论上。取决于实现我想,因为它不是强制的标准,但最常见的是没有内存开销。

This will be the same, both only have a member double. Theoretically. Depends on the implementation I guess, as it's not mandated by the standard, but most commonly there will be no memory overhead.

注意对象 MyClass1 通过指向 Derived 的指针导致未定义的行为,因为没有 / code> destructor。

Note that deleting an object MyClass1 through a pointer to Derived results in undefined behaviour, because there's no virtual destructor.

注2 没有多态性的继承是代码气味。不是说错了,但在大多数情况下,组成更好。

Note 2 inheritance without polymorphism is a code smell. Not saying it's wrong, but in most cases composition is better.

这篇关于在C ++中继承的运行时成本(没有虚拟)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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