c++qtauto-ptr

Qt and auto_ptr


I just discovered the concept of an auto_ptr and am liking it! As Qt often requires a QList or QVector<(some QObject or QWidget) *>, is there any concrete reason why auto_ptr should be avoided. If I'm right, it allows you to replace this:

std::vector<MyClass*> vec;
/* add several elements to the vector and do stuff with them */
for(size_t i=0; i<vec.length(); ++i)
{
    delete vec[i];
}
vec.clear();

with somthing much shorter (ie no cleanup)

std::vector<auto_ptr<MyClass>> vec;
/* add several elements to the vector and do stuff with them */
// no need for the delete loop

...Can Qt still work its shared memory magic with auto_ptr's? Does the parent-child automagic memory management still function transparently? Thanks


Solution

  • Qt has its own smart pointer classes that are in many ways superior to std::auto_ptr, specifically in that some of them can be put into containers with no issues. std::auto_ptr has ownership-transfer copy semantics, and so will not work as expected if you try to put it into a container.

    Try using QSharedPointer. It's a reference counted smart pointer that deletes its contained object when there are no more copies of the smart pointer left. Unlike std::auto_ptr there can be multiple copies of the same QSharedPointer at once, and therefore it plays well with containers.