开发者

Inheritance Costs in C++

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜