Reputation: 8315
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.
Upvotes: 0
Views: 38
Reputation: 307
Ownership is exactly that. i.e the responsibility to delete an object. It does not imply or even encourage that the owning entity create the owned entity.
It is absolutely ok for the creation to take place somewhere else as long as ownership is passed in an obvious way.
For C++, use
std::<unique_ptr>
rather than documentation to make this explicit. It will also allow your code to do automatic cleanup.
use
std::<shared_ptr>
when the ownership is not clear. i.e it is not deterministic or clear which entity should end up actually deleting the object.
For more information read about smart pointers. https://en.wikipedia.org/wiki/Smart_pointer
Upvotes: 1
Reputation: 62583
EDIT
Read the question. You do not need a special container class. You need a vector of std::unique_ptr
.
Upvotes: 3