我从未想到C++具有指针协变性,因此会让你像这样自毁长城:
struct Base
{
Base() : a(5) {}
int a;
};
struct Child1 : public Base
{
Child1() : b(7) {}
int b;
int bar() { return b;}
};
struct Child2 : public Base
{
Child2(): c(8) {}
int c;
};
int main()
{
Child1 children1[2];
Base * b = children1;
Child2 child2;
b[1] = child2; // <------- now the first element of Child1 array was assigned a value of type Child2
std::cout << children1[0].bar() << children1[1].bar(); // prints 57
}
这是未定义行为吗?有没有办法防止它,或者至少从编译器得到警告?
b[0]
是第零个元素,但也是第一个元素。而且,那个切片已经被定义:它只是执行了operator=(Base&)
。这不太可能有任何有用的作用,但确实是被定义了的。 - Yakk - Adam Nevraumont