C++ 的开销 没有虚函数的继承
在 C++ 中,与继承没有虚函数的基类相关的开销(内存/CPU)是多少? 它和直接复制+粘贴班级成员一样好吗?
class a
{
public:
void get();
protected:
int _px;
}
class b : public a
{
}
和....相比
class a
{
public:
void get();
protected:
int _px;
}
class b
{
public:
void get();
protected:
int _px;
}
In C++, what's the overhead (memory/cpu) associated with inheriting a base class that has no virtual functions? Is it as good as a straight up copy+paste of class members?
class a
{
public:
void get();
protected:
int _px;
}
class b : public a
{
}
compared with
class a
{
public:
void get();
protected:
int _px;
}
class b
{
public:
void get();
protected:
int _px;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
与复制和过去相比,使用继承时可能会产生轻微的内存开销(由于填充),请考虑以下类定义:
sizeof(B1) 可能为 12,而 sizeof(B2) 可能仅为 8。这是因为基类 A 单独填充为 8 字节,然后 B1 再次填充为 12 字节。
There might a be slight memory overhead (due to padding) when using inheritance compared to copy and past, consider the following class definitions:
sizeof(B1) will probably be 12, whereas sizeof(B2) might just be 8. This is because the base class A gets padded separately to 8 bytes and then B1 gets padded again to 12 bytes.
编译时间会稍微长一些,并且不会有额外的运行时开销。 从优化器的角度来看,非虚拟方法与过程相同——可以仅使用其内存地址来调用它们,而无需虚拟方法表的开销。
It will take very slightly longer to compile, and there will be no additional runtime overhead. From the optimizer's perspective, non-virtual methods are the same as procedures -- they can be called using only their memory address, without overhead from a virtual method table.
如果您忘记了虚拟继承,那么在内存和性能方面,拥有基类与拥有同一类的成员是等效的。 但有时它可能会更好(例如,空类的大小至少为 1,但空基类通常可能没有开销)。
If you forget virtual inheritance, having a base class is equivalent, memory and performance wise, to having a member of the same class. Excepted that it can sometimes be even better (for instance an empty class has a size of at least one but having an empty base class may often have no overhead).
如果您可能有一个 Base* 类型的指针指向 Derived* 类型的对象,那么您可能需要一个虚拟析构函数,并且您原来的前提不再适用。 如果派生类有一个空的析构函数,并且它没有成员或者它们都是 POD 类型,那么您可以不用虚拟析构函数,但通常最好谨慎行事并从一开始就将其设为虚拟。
编译器将生成对实现每个非虚拟成员函数的代码的直接调用,因此没有开销。
If you might have a pointer of type Base* that points to an object of type Derived*, you probably need a virtual destructor and your original premise no longer applies. If the derived class has an empty destructor, and it has no members or they're all POD types, you can get away without a virtual destructor, but it's usually better to play it safe and make it virtual from the start.
The compiler will generate a direct call to the code implementing each non-virtual member function, thus there is no overhead.
不是真的,它只是增加了基类的内存。 您可以在此处的 C++ 常见问题解答中了解更多信息
Not really, it only increased the memory by the base class. You can read more in here in C++ FAQ