In my application I am creating and returning an array filled with dynamically allocated objects from a derived class like this:
void someGetter(std:vector<DerivedClass> & returnV)
{
BaseClass* base = object->clone(); // "object" is a "unique_ptr<BaseClass>"
DerivedClass* derived = dynamic_cast<DerivedClass*> (base);
if (derived != nullptr)
{
returnV.push_back(*derived);
}
else
{
delete base;
}
}
This obviously creates a memory leak (valgrinds helps me here) because derived is never deleted.
I have tried to free the allocated memory like this:
delete &returnV[0];
It doesn’t give any compilation errors/warnings and the code still runs fine. but valgrind reports a few additional errors (invalid read, invalid free) on that line of code and the leak is still there.
Is there any way to free the memory returned like this? Or should i return unique_ptr’s instead of the objects ?
First off, the design seems very questionable to me: You have at once a polymorphic hierarchy, and also a container that holds values of a specific member of that hierarchy. There’s no end to the problems you’re inviting. It would seem far more sensible to have a
std::vector<std::unique_ptr<Base>>.Anyway, here’s a moderately safe and efficient way to insert into the container only those objects whose dynamic type matches precisely. It assumes that every class in the hierarchy has an accessible copy constructor.
The semantics of this are slightly different from yours, because your code would allow the case where
*objectis of a strictly more derived type thanDerivedClass, and the copying into the vector would slice the object. The present code does not suffer from this problem.Update (after your comment): If
DerivedClassis indeedfinal(and please mark it as such!), then the following does withouttypeid: