QList和shared_ptr
你怎么认为? 这是正确的还是存在内存泄漏?
来源:
#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;
}
输出:
6
destroying A(6)
What do you think? Is this correct or are there memory leaks?
Source:
#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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看来是对的。 Boost的shared_ptr是一个引用计数指针。 如果对象之间没有循环引用,引用计数能够回收内存。 在您的情况下,A 类的对象不引用任何其他对象。 因此,您可以无忧无虑地使用shared_ptr。 此外,所有权语义允许在 STL(和 Qt)容器中使用共享指针。
It seems correct. Boost's shared_ptr is a reference counting pointer. Reference counting is able to reclaim memory if there are no circular references between objects. In your case, objects of class A do not reference any other objects. Thus, you can use shared_ptr without worries. Also, the ownership semantics allow shared_ptrs to be used in STL (and Qt) containers.
这段代码看起来非常好。
如果您正在寻求建议,也许您可以提供有关将shared_ptr与QList一起使用的目的的更多信息,可能有一种“Qt”方式可以做到这一点,而无需使用shared_ptr等大枪。
This code looks perfectly fine.
If you're seeking advice perhaps you could provide more info on the purpose of using shared_ptr with QList, there might be a "Qt" way of doing this without pulling the big guns such as shared_ptr.
如果不知道为什么
A
对象的shared_ptr
列表首先存在,就很难提出任何建议。查看所有权智能指针的语义。 也许对你有帮助。
其他一些可以改进的地方:
1. 在 ctor 中使用初始化列表,例如:
2.
int _tmain(int argc, _TCHAR* argv[]) 不是标准签名;
使用
或仅:
It is difficult to suggest anything without knowing why the list of
shared_ptr
s ofA
objects exist in the first place.Take a look at the ownership semantics of smart pointers. Maybe of help to you.
Some other things that can be improved:
1. Use initializer lists in ctor like:
2.
int _tmain(int argc, _TCHAR* argv[])
is not a Standard signature;Use
or just:
如果您不使用智能指针,则必须自己删除列表元素。
来源:
输出:
不好。
If you're not using a smart pointer, you have to delete the list elements by yourself.
Source:
Output:
Not good.