Qt and auto_ptr

I just opened the concept of auto_ptr and I like it! Since Qt often requires a QList or QVector <(some QObject or QWidget) *>, is there any specific reason why auto_ptr should be avoided. If I'm right, this allows me 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 much less (i.e. no cleaning)

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 with memory magic with auto_ptr? Does automatic parental memory management support transparently? Thanks

+3
source share
3 answers

Qt , std::auto_ptr, , , . std::auto_ptr , .

QSharedPointer. , , . std::auto_ptr QSharedPointer, .

+12

, , boost.

, , , , (.. -). , :

boost::ptr_vector<MyClass>   v;
v.push_back(new MyClass(12));

std::for_each(v.begin(), v.end(), DoStuff());

// Destroyed here.
+2

std::auto_ptr std::vector, std::vector , , std::auto_ptr . , std::auto_ptr, , , . ( , auto_ptr , , , , ).

Use shared_ptrthat is often available like boost::shared_ptror in Visual C ++ std::tr1::shared_ptr, and which will be in the standard C ++ 0x library or use any Qt. They can be copied and therefore can be included in containers.

+1
source

Source: https://habr.com/ru/post/1746598/


All Articles