Search code examples
c++classpolymorphismraiiownership

Owner object that takes pre-created values ? Wrong design?


It is a wrong design to have an object that is considered as the owner of it's components (or items in the case of an array / map) but that only deletes them and doesn't construct them ?

For example if I have a hierarchy of classes :

class A { public: virtual ~A() { } };
class A1 : public A { };
class A2 : public A { };

And if need to store several instances of A1 and/or A2 into a same array and using polymorphism (i.e vector< A * >), is it a correct design to create a class that encapsulates the vector to delete the elements ?

class ArrayOfA
{
private:
    std::vector< A * > m_items;
public:
    ~ArrayOfA() { for( auto a : m_items ) delete a; }
    void add( A * a ) { m_items.push_back( a ); }
};

Which is then used as follows :

ArrayOfA arr;
arr.add( new A1() );
arr.add( new A2() );
throw; // Do not care about release for RAII

The problem is if someone adds an A that is owned by something else. But this should not be a problem if it is clearly stated in the documentation that ArrayOfA will delete it. But for some reason it feels like this design is flawn.

I know that it is possible using C++11 to use variadic templates to pass the parameters of the constructors of A1 or A2 to ArrayOfA::add() so that the object makes both the new and the delete, but I don't want to use that.


Solution

  • EDIT

    Read the question. You do not need a special container class. You need a vector of std::unique_ptr.