Can there be a C++ type that takes 0 bytes

后端 未结 6 1475
Happy的楠姐
Happy的楠姐 2021-01-02 14:21

I\'m trying to declare a C++ variable that takes up zero bytes. Its in a union, and I started with the type as int[0]. I don\'t know if that is actually zero bytes (although

6条回答
  •  不知归路
    2021-01-02 15:17

    You cannot instantiate any data type in C++ that takes up zero bytes. The Standard dictates than an empty class, such as:

    class Empty {};
    

    ...will result in the following being true:

    Empty emp;
    assert( sizeof(emp) != 0 );
    

    The reason for this is so that you can take the address of the object.

    EDIT: I originally said the sizeof would be 1, but per @Als' comment, I have found the relevant passage in the Standard, and it is indeed simply non-zero:

    [Classes] §9/3

    Complete objects and member subobjects of class type shall have nonzero size

提交回复
热议问题