我知道C++不支持容器元素的协方差,就像在Java或C#中一样.所以下面的代码可能是未定义的行为:
#include <vector>
struct A {};
struct B : A {};
std::vector<B*> test;
std::vector<A*>* foo = reinterpret_cast<std::vector<A*>*>(&test);
Run Code Online (Sandbox Code Playgroud)
毫不奇怪,我在建议这个解决另一个问题时收到了downvotes .
但是C++标准的哪一部分确切地告诉我这将导致未定义的行为?它的保证,无论std::vector<A*>和std::vector<B*>他们的指针存储在内存中的continguous块.它也保证了sizeof(A*) == sizeof(B*).最后,A* a = new B完全合法.
那么我标准的标准是什么坏的(风格除外)?