开发者

Nested empty class

开发者 https://www.devze.com 2023-01-26 06:38 出处:网络
I have the following code class nest_empty { class empty{}; }; 开发者_开发技巧 Will the size of nest_empty be 1 (on my implementation sizof an empty class is 1)? If yes why? Can nest_empty be consid

I have the following code

class nest_empty
{
   class empty{};
};
开发者_开发技巧

Will the size of nest_empty be 1 (on my implementation sizof an empty class is 1)? If yes why? Can nest_empty be considered as an empty class?

EDIT:

class nest_empty
{
   class empty{};
   empty d;
};

Will the size of nest_empty still be 1? If yes why?


Your first version of nest_empty is an empty class (no non-static data members, and no non-empty bases), so if they have size 1 in your implementation, it has size 1.

"Why" is because empty classes have size 1 on your implementation, which in turn is because they can't have size 0 (the standard forbids it), and your implementer has chosen 1.

Your second nest_empty is not an empty class (it has a non-static data member). It could legally have size 1, since its only non-static data member, d, is of type empty, which is an empty class and hence presumably of size 1.

I can't tell you whether it actually will have size 1 on your implementation, though. Ask your compiler.


Yes. empty is just in the namespace of nest_empty.

To be clearer, the line class nest_empty{}; simply defines nest_empty. It does not declare any member in empty.


It's not mandatory for sizeof(nest_empty) to be 1, but it won't be zero.

$9.3 says: Complete objects and member subobjects of class type shall have nonzero size.

This is needed because if you create an array of nest_empty, each one has to have a different address from the other.

EDIT

Most probably, sizeof(nest_empty) will yield the same result in both version, but that it's not mandated. The only thing the standard says is that empty class will have nonzero size.

0

精彩评论

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