Is padding between members of a class of the same type the same?

The following class contains some elements of the same type:

template <typename T>
class MyClass
{
    T m0;
    T m1;
    T m2;
    T m3;
    T m4;
    //...
};

All members are declared without an intermediate access specifier and therefore it is highlighted that later members have higher addresses (ISO / IEC 14882: 9.2.12). The same paragraph says:

Requirements for alignment of the implementation may lead to the fact that two neighboring elements will not be allocated immediately after each Other; therefore, space may be required to manage virtual functions (10.3) and virtual base classes (10.1).

Now suppose MyClass has no virtual functions and virtual base classes. Is the following always true?

//inside a member function of MyClass

(char*)&m0 == (char*)&m0 + ((char*)&m1-(char*)&m0) * 0
(char*)&m1 == (char*)&m0 + ((char*)&m1-(char*)&m0) * 1
(char*)&m2 == (char*)&m0 + ((char*)&m1-(char*)&m0) * 2
(char*)&m3 == (char*)&m0 + ((char*)&m1-(char*)&m0) * 3
(char*)&m4 == (char*)&m0 + ((char*)&m1-(char*)&m0) * 4

, ( - ...)? : sizeof (T) == 4 alignof (T) == 8, 4 padding-bytes . 12 padding-bytes m2 m3?

, MyClass ? , MyClass (, vtable-ptr) ? T? , , T T, :

template <typename T>
class MyClass
{
    T m0;
    //space to manage virtual functions and base classes of m0
    //padding
    T m1;
    //space to manage virtual functions and base classes of m1
    //padding
    T m2;
    //space to manage virtual functions and base classes of m2
    //...
};

.

+3
1

. , , . " ..." - , .

, T m[5], &(this->m[1]) - &(this->m[0]) == 1.

: " , MyClass (, vtable-ptr) ?" , , . ( a T T[5]), .

+3

Source: https://habr.com/ru/post/1752260/


All Articles