C++ sizeof instance resolution

  • 2020-04-02 01:13:29
  • OfStack

Using sizeof in C++ is much more complicated than using C because C++ classes have static static variables, virtual virtual functions, inheritance, derivation, and so on. Sizeof is a monocular operator of C, such as the other C operators ++, --, etc. It's not a function. The sizeof operator gives the storage sizeof its operands in bytes.
Sizeof can be used in three forms: sizeof(var_name) or sizeof var_name or sizeof(var_type).

(ignore the construction and destructor in the column)


class A  
{  
    public: 
        void hello(){}  
};  
sizeof(A)= 1;

Definitely not zero. For example, if it is zero, declare an array of class A A[10] objects, and each object takes up zero space, then there is no way to distinguish A[0],A[1]... .

Because A is an empty class, the occupation byte is 1 to distinguish two different objects, which can also be regarded as A placeholder, the address of the byte is also the address of the object. But the one here is not absolute, it's just the compiler setting it that way.
2.


class B  
{  
    public: 
         void hello(){} 
         static int i;
};  
    sizeof(B) = 1;

Since the static variable is Shared in the class, it allocates space in the static area, which is allocated at compile time and does not occupy class memory.
(1) :

classC
{  
    public: 
        virtual void hello(){} 
};
sizeof(C)= 4;

Class B has virtual functions, corresponding to the existence of virtual table pointer, take up four bytes, exactly one pointer space. At the same time, if there are more than one virtual function or more than one class inherited from the C class, the virtual function only takes 4 bytes, such as [example 4] :
(1) :

class D : public C
{ 
    public: 
        virtual void world(){} 
        virtual  void nihao(){}
};
sizeof(D)= 4;

(1) :

class E
{  
    public: 
          virtual void hello(){} 
          virtual void world(){} 
          staticint i;
          static int j;
          int k;
};
     sizeof(E) = 8;

I hope it helped you.


Related articles: