Bạn nghĩ sao? Điều này có đúng hay có rò rỉ bộ nhớ không?QList và shared_ptr
Nguồn:
#include <QList.h>
#include <boost/shared_ptr.hpp>
#include <iostream>
class A {
private:
int m_data;
public:
A(int value=0) { m_data = value; }
~A() { std::cout << "destroying A(" << m_data << ")" << std::endl; }
operator int() const { return m_data; }
};
int _tmain(int argc, _TCHAR* argv[])
{
QList<boost::shared_ptr<A> > list;
list.append(boost::shared_ptr<A>(new A(6)));
std::cout << int(*(list.at(0))) << std::endl;
return 0;
}
Output:
6
destroying A(6)
Là một sidenote: không sử dụng 'QList' trong đó 'sizeof (T)> sizeof (void *)' (và 'sizeof (shared_ptr ) == 2 * sizof (void *)', thường), vì trong trường hợp đó, 'QList' sẽ sao chép' '' 'các phần tử vào danh sách (trái ngược với việc giữ nó theo giá trị). Sử dụng 'QVector' hoặc' std :: vector' để thay thế. –