Question

I have QVector<QSharedPointer<SomeData> > DataVec as a field of one class in a big objected-oriented project. Program gets memory overflow during cycled execution of code part, where large memory is allocated, controlled by QSharedPointers.

During program run cycle, DataVec is filled with

DataVec.push_back(QSharedPointer<SomeData>(new SomeData()));

Will QSharedPointer be deleted (released) after calling DataVec.pop.back() or DataVec.clear()?

I think: no. We must call explicitly destructor for QSharedPointer (I cannot see also the method like boost::shared_ptr::reset() in Qt). Than, SomeData default destructor (SomeData have only standard Qt containers as fields) will be called if we have no more QSharedPointers that point to SomeData instance concerned, and the memory will be released. Now, I only do pop_back(): it seems, I just loose pointers to unreleased data (after execution, valgrind indicates I have definitely lost blocks, and I suppose they originate from here).

So, finally, am I right? And how can I delete QSharedPointer from container the right way?

EDIT 1: The method like boost::shared_ptr::reset() in Qt is QSharedPointer::clear().

Was it helpful?

Solution

QVector will call the destructor of its item when the item is removed from it using pop_back, clear or any other way.

If there is a shared pointer to an object in the vector and there is no more shared pointers to this object anywhere in the program, removing a shared pointer from the vector will definitely cause object deleting.

If there are shared pointers to this object somewhere else, the object will not be deleted until all references are removed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top