Storing heterogeneous objects in a vector with stacked objects

Saving objects in a heterogeneous vector with stacked objects

Hello,

Say I have an abstract CA class derived from CA1, CA2, and possibly others.

I want to put objects of these derived types in a vector that I injected into the CB class. To get polymorphism correctly, I need to save the pointer vector:

class CB
{
    std::vector <CA*> v;
};

Now, let's say I have the following main function:

int main()
{
    CB b;
    CA1 a1;
    CA2 a2;
    b.Store( a1 );
    b.Store( a2 );
}

How to write a method in a void CB::Store(const CA&)simple way, so the saved objects are saved when the original objects are destroyed (which is not found in the simple example above).

, , , ? , RTTI , , ( ) , . , ?

?

( !)

+3
3

:

struct CA
{
    virtual CA *clone(void) const = 0;
    virtual ~CA() {} // And so on for base classes.
}

struct CA1 : public CA
{
    virtual CA *clone(void) const
    {
        return new CA1(*this);
    }
}

struct CA2 : public CA
{
    virtual CA *clone(void) const
    {
        return new CA2(*this);
    }
}

, :

void CB::Store(const CA& pObject)
{
    CA *cloned = pObject.clone();
}

Boost.Pointer Container. :

boost::ptr_vector<CA> objects;

void CB::Store(const CA& pObject)
{
    objects.push_back(pObject->clone());
}

. . .

+7

, clone() , .

class CA
{
   public:
   virtual ~CA() {}
   virtual CA* clone() const = 0;
}

class CA1 : public CA
{ 
    public:
    virtual CA *clone() const
    {
       return new CA1(*this);
    }
};
+2

templatize Store :

class CB
{
public:
    template<class T>
    void Store(const T& t)
    {
         v.push_back(new T(t));
    }

private:
    std::vector <CA*> v;
};

: "clone()", , . , :

CB b;
CA1 a1;
CA2 a2;
b.Store(a1);
b.Store(a2);

:

CA1 a1;
CA* a = &a1;
b.Store(*a); //Ouch! this creates a new CA, not a CA1

ctor CA . , CA1, .

+1
source

Source: https://habr.com/ru/post/1720684/


All Articles