Getting a vector into a function that expects a vector<Base*>

后端 未结 9 1866
日久生厌
日久生厌 2020-11-29 07:11

Consider these classes.

class Base
{
   ...
};

class Derived : public Base
{
   ...
};

this function

void BaseFoo( std::ve         


        
9条回答
  •  星月不相逢
    2020-11-29 08:10

    If std::vector supported what you're asking for, then it would be possible to defeat the C++ type system without using any casts (edit: ChrisN's link to the C++ FAQ Lite talks about the same issue):

    class Base {};
    class Derived1 : public Base {};
    class Derived2 : public Base {};
    
    void pushStuff(std::vector& vec) {
        vec.push_back(new Derived2);
        vec.push_back(new Base);
    }
    
    ...
    std::vector vec;
    pushStuff(vec); // Not legal
    // Now vec contains a Derived2 and a Base!
    

    Since your BaseFoo() function takes the vector by value, it cannot modify the original vector that you passed in, so what I wrote would not be possible. But if it takes a non-const reference and you use reinterpret_cast&>() to pass your std::vector, you might not get the result that you want, and your program might crash.

    Java arrays support covariant subtyping, and this requires Java to do a runtime type check every time you store a value in an array. This too is undesirable.

提交回复
热议问题