开发者

Inheritance Costs in C++

开发者 https://www.devze.com 2023-01-06 03:06 出处:网络
Taking the following snippet as an example: struct Foo { typedef int type; }; class Bar : private Foo { }; class Baz

Taking the following snippet as an example:

struct Foo
{
  typedef int type;
};

class Bar : private Foo
{
};

class Baz
{
};

As you can see, no virtual functions exist in this relationship.开发者_如何学Go Since this is the case, are the the following assumptions accurate as far as the language is concerned?

  • No virtual function table will be created in Bar.
  • sizeof(Bar) == sizeof(Baz)

Basically, I'm trying to figure out if I'll be paying any sort of penalty for doing this. My initial testing (albeit on a single compiler) indicates that my assertions are valid, but I'm not sure if this is my compiler's optimizer or the language specification that's responsible for what I'm seeing.


According to the standard, Bar is not a POD (plain old data) type, because it has a base. As a result, the standard gives C++ compilers wide latitude with what they do with such a type.

However, very few compilers are going to do anything insane here. The one thing you probably have to look out for is the Empty Base Optimization. For various technical reasons, the C++ standard requires that any instance be allocated storage space. For some compilers, Foo will be allocated dedicated space in the bar class. Compilers which implement the Empty Base Optimization (most all in modern use) will remove the empty base, however.

If the given compiler does not implement EBO, then sizeof(foo) will be at least twice sizeof(baz).


Yeah, without any virtual members or member variables, there shouldn't be a size difference.


As far as I know the compiler will optimize this correctly, if any optimizing is needed at all.

0

精彩评论

暂无评论...
验证码 换一张
取 消