Should an empty base class affect the layout of the derived class?

前端 未结 4 723
一个人的身影
一个人的身影 2021-01-18 19:42

The C++ standard (quoting from draft n3242) says the following about subobjects [intro.object]:

Unless an object is a bit-field or a base class subobj

4条回答
  •  时光说笑
    2021-01-18 20:06

    There are good explanations in this thread. I just wanted to add that to work around this structure bloat issue you can simply make empty class a template, so that instantiating it with a different template argument makes it a different class:

    template
    struct empty { };
    struct member: empty { };
    struct derived: empty { member m; };
    
    int main(void)
    {
        printf("%d\n", sizeof(derived));
        return 0;
    }
    

    Outputs 1.

    This is the reason to avoid using boost::noncopyable in large projects.

提交回复
热议问题