Qt和auto_ptr

rub*_*nvb 3 c++ qt auto-ptr

我刚刚发现了auto_ptr的概念,我很喜欢它!由于Qt经常需要QList或QVector <(某些QObject或QWidget)*>,是否应该避免使用auto_ptr的具体原因.如果我是对的,它允许你替换它:

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();
Run Code Online (Sandbox Code Playgroud)

用更短的东西(即没有清理)

std::vector<auto_ptr<MyClass>> vec;
/* add several elements to the vector and do stuff with them */
// no need for the delete loop
Run Code Online (Sandbox Code Playgroud)

... Qt仍然可以使用auto_ptr进行共享内存魔术吗?父子自动记忆管理是否仍然透明地运作?谢谢

Tyl*_*nry 12

Qt有自己的智能指针类,它们在许多方面都优于其中std::auto_ptr,特别是因为它们中的一些可以放入容器中而没有任何问题.std::auto_ptr具有所有权转移复制语义,因此如果您尝试将其放入容器中,则无法按预期工作.

尝试使用QSharedPointer.它是一个引用计数智能指针,当没有更多的智能指针副本时,它会删除其包含的对象.与std::auto_ptr同时可以存在多个副本不同QSharedPointer,因此它可以很好地与容器配合使用.