You have a few choices:
You can make it clear that the vector does not own the objects in it, only the pointers to them. It then becomes the responsibility of all code that uses this vector to allocate and delete the objects itself.
You can use a boost ptr_vector
for this. The vector will own the objects it contains pointers to. You'll need to write a helper function to duplicate the objects so that x = y;
will work. (Since x
will need to own its own copy of every object in y
.)
You can use smart pointers, such as boost::shared_ptr
, for this. If you do x = y;
, the two vectors will refer to the same objects, such that changing the value in one will change the value in the other. The vectors will share ownership of the objects and can return safe references to the objects in them. The objects will self-destruct when they are no longer needed.
You can use a vector of boost::any
objects. This performs poorly but is very flexible.
But it really comes down to the classic question: What are you trying to do? Are you trying to manage the lifetimes of objects? If you duplicate a vector, what should happen? Should that duplicate the underlying objects? Do you need polymorphism? Are you using pointers to avoid slicing? And so on. Explain your use case and you'll get better solution suggestions.
Update: Your use of a vector of pointers seems simple and safe (so long as you don't try to copy-construct a vector, assign it, or anything like that). That your delete
loop is crashing suggests possibly a bug in your destructor.
Update2: Yep.
laboratory::~laboratory()
{
delete stationUsers;
}
This is wrong because stationUsers
wasn't allocated with new
but with new[]
.