c ++ 11中的POD类型和继承:为什么无法继承和扩展,而仍然是POD类型

时间:2018-06-27 22:58:49

标签: c++11 inheritance standard-layout

我认为最好用一个例子来解释:

    #include <iostream>

struct A
{
    int a;
};
struct B
{
    A a;
    int b;
};
struct C: A
{
    int c;
};

static inline std::ostream& operator<< (std::ostream& os, const A& a)
{ return os << a.a; }
static inline std::ostream& operator<< (std::ostream& os, const B& b)
{ return os << b.a << " " << b.b; }
static inline std::ostream& operator<< (std::ostream& os, const C& c)
{ return os << c.a << " " << c.c; }

static_assert(std::is_pod<B>::value, "B");
static_assert(std::is_pod<A>::value, "A");
static_assert(std::is_trivial<C>::value, "C");
//static_assert(std::is_pod<C>::value, "C");

int main()
{
    std::cout << "sizeof(A) " << sizeof(A) << std::endl;
    std::cout << "sizeof(B) " << sizeof(B) << std::endl;
    std::cout << "sizeof(C) " << sizeof(C) << std::endl;
    B b = B{14,42};
    std::cout << "b " << b << std::endl;
    C c; c.a=15; c.c=43;
    std::cout << "c " << c << std::endl;
    B* bp = &b;
    std::cout << "(C)b " << *(C*)(bp) << std::endl;
    C* cp = &c;
    std::cout << "(B)c " << *(B*)(cp) << std::endl;

    return 0;
}

输出:

sizeof(A) 4
sizeof(B) 8
sizeof(C) 8
b 14 42
c 15 43
(C)b 14 42
(B)c 15 43

为什么C不符合standard_layout的条件。如我所料,它与B具有相同的内存布局。可能有什么不同?

0 个答案:

没有答案