Empty base class optimization

Below is a simple test on ebco, I compiled it on both vc9 and g ++. The outputs are different for both compilers. I want to know if vc behavior is consistent.

#include <iostream>

class empty
{
};

class empty_one : public empty {};
class empty_two : public empty {};

class non_empty
    : public empty_one
    , public empty_two
{
};

int main()
{
    std::cout << "sizeof(empty): " << sizeof(empty) << std::endl;
    std::cout << "sizeof(empty_one): " << sizeof(empty_one) << std::endl;
    std::cout << "sizeof(empty_two): " << sizeof(empty_two) << std::endl;
    std::cout << "sizeof(non_empty): " << sizeof(non_empty) << std::endl;

    std::cout << std::endl;

    non_empty a[2];

    void* pe10 = static_cast<empty*>(static_cast<empty_one*>(&a[0]));
    void* pe20 = static_cast<empty*>(static_cast<empty_two*>(&a[0]));
    std::cout << "address of non_empty[0]: " << &a[0] << std::endl;
    std::cout << "address of empty of empty_one: " << pe10 << std::endl;
    std::cout << "address of empty of empty_two: " << pe20 << std::endl;

    std::cout << std::endl;

    void* pe11 = static_cast<empty*>(static_cast<empty_one*>(&a[1]));
    void* pe21 = static_cast<empty*>(static_cast<empty_two*>(&a[1]));
    std::cout << "address of non_empty[1]: " << &a[1] << std::endl;
    std::cout << "address of empty of empty_one: " << pe11 << std::endl;
    std::cout << "address of empty of empty_two: " << pe21 << std::endl;
}

On vc,

pe20 == pe11. (test1)

Can two sub-objects of two objects have the same address? Is this consistent?

Besides,

pe20 >= &a[0] + sizeof(a[0]) (test2)

Can the address of a sub-object pass the end of the object?

In g ++, the above two tests fail.

EDIT : in a standard draft of C ++ 0x, 1.8 / 6,

If the object is a bit field or a subobject of a base class of zero size, the address of this object is the address of the first byte that it occupies. Two different objects, which are neither bit fields, nor subobjects of a base class of zero size, must have different addresses

, , , . , - . , test1 ?

+5
2

pe10 == pe11. - ? ?

, . , .

, V++ ? MSV++ 2008, :

alt text

, pe20==pe11? , , . MSV++ 2008 !

GCC ; : http://www.ideone.com/Cf2Ov


:

(EBO)

+1

pe10 == pe11. - ? ?

Nopes!

, , .

, - . . !

+1

All Articles