[英]Is it safe to return a vector of std::shared_ptr?
Is my code in risk of memory-leak for returning vector of std::shared_ptr?我的代码是否存在返回 std::shared_ptr 向量的内存泄漏风险? I think it's safe because the reference count will not be zero till the end of main function.
我认为这是安全的,因为在主 function 结束之前,引用计数不会为零。 Am I right?
我对吗?
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class A {
public:
A(int v):a(v){}
int a;
};
typedef std::shared_ptr<A> APtr;
vector<APtr> test() {
APtr x(new A(1));
APtr y(new A(2));
APtr z(new A(3));
APtr a(new A(4));
return vector<APtr>({x, y, z, a});
}
int main()
{
cout << "Hello World" << endl;
vector<APtr> b = test();
for(auto k : b) {
cout << k->a << "\n";
}
return 0;
}
Yes, this is safe and memory-leak free.是的,这是安全且无内存泄漏的。 Your
test
function creates the pointers, and they'll all have a reference count of one.您的
test
function 创建了指针,它们的引用计数都为 1。 Once the function returns, they're copied into b
which increases the reference count, then they go out of scope and decrease the reference count back down to 1. The A
are all cleaned up correctly at the end of main
.一旦 function 返回,它们就会被复制到
b
中,这会增加引用计数,然后它们 go 会从 scope 中取出,并将引用计数减少到main
1 A
末尾。
Putting a breakpoint (or cout
statement) in ~A
should also show you this correctly.在
~A
中放置断点(或cout
语句)也应该正确地显示这一点。 One final minor note, you should prefer make_shared
over new
最后一点,你应该更喜欢
make_shared
而不是new
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.