Container covariance in C++

前端 未结 4 1060
清酒与你
清酒与你 2020-12-06 00:10

I know that C++ doesn\'t support covariance for containers elements, as in Java or C#. So the following code probably is undefined behavior:

#include 

        
4条回答
  •  旧时难觅i
    2020-12-06 01:07

    The general problem with covariance in containers is the following:

    Let's say your cast would work and be legal (it isn't but let's assume it is for the following example):

    #include 
    struct A {};
    struct B : A { public: int Method(int x, int z); };
    struct C : A { public: bool Method(char y); };
    std::vector test;
    std::vector* foo = reinterpret_cast*>(&test);
    foo->push_back(new C);
    test[0]->Method(7, 99); // What should happen here???
    

    So you have also reinterpret-casted a C* to a B*...

    Actually I don't know how .NET and Java manage this (I think they throw an exception when trying to insert a C).

提交回复
热议问题