C++: What is the size of an object of an empty class?

后端 未结 16 1612
悲&欢浪女
悲&欢浪女 2020-11-22 11:54

I was wondering what could be the size of an object of an empty class. It surely could not be 0 bytes since it should be possible to reference and

相关标签:
16条回答
  • 2020-11-22 12:25

    It is because of this pointer , although pointer is (integer) of 4 byte but it refer to a one memory location ( one Unit ) which is 1 byte.

    0 讨论(0)
  • 2020-11-22 12:29

    This may help u :-) http://bytes.com/topic/c/insights/660463-sizeof-empty-class-structure-1-a

    The sizeof an empty class or structure is 1

    The reason this happens boils down to properly implementing the standard, one of the things the C++ standard says is that "no object shall have the same address in memory as any other variable".... What is the easiest way to ensure this? Make sure that all types have a non-zero size. In order to achieve this the compiler adds a dummy byte to structures and classes that have no data members and no virtual functions so that they have a size of 1 rather than a size of 0 and then they are guaranteed to have a unique memory address.

    0 讨论(0)
  • 2020-11-22 12:32

    the reason for class with no data members but having size 1 byte is that the this*strong text* must be stored in memory so that a reference or pointer can point to the object of that class

    0 讨论(0)
  • 2020-11-22 12:33

    There is an exception: 0-length arrays

    #include <iostream>
    
    class CompletlyEmpty {
      char NO_DATA[0];
    };
    
    int main(int argc, const char** argv) {
      std::cout << sizeof(CompletlyEmpty) << '\n';
    }
    
    0 讨论(0)
  • 2020-11-22 12:36

    empty class -that class does not contain any content.

    any class which is not empty will be represented by its content in memory.

    now how empty class will be represented in memory? as it has no content no way to show its existance in memory, but class is present ,it is mandatory to show its presence in memory. To show empty class presence in memory 1 byte is required.

    0 讨论(0)
  • 2020-11-22 12:36
    #include<iostream>
    using namespace std;
    
    
        class Empty { };
        int main()
        {
            Empty* e1 = new Empty;
            Empty* e2 = new Empty;
    
            if (e1 == e2)
                cout << "Alas same address of two objects" << endl;
            else
                cout << "Okay it's Fine to have different addresses" << endl;
    
            return 0;
        }
    

    Output: Okay it's Fine to have different addresses

    Returning size 1 ensures that the two objects will not have the same address.

    0 讨论(0)
提交回复
热议问题