返回shared_ptr时的引用计数
下面的代码是否意味着当这个函数返回时,这个类内部的request对象仍然持有这个对象的引用?
boost::shared_ptr<Request> RequestList::GetRequest()
{
boost::mutex::scoped_lock(listmtx);
request = boost::shared_ptr<Request>(new Request());
return request;
}
使用:
request = requests->GetRequest(); //Ref count is two on request object when it returns??
即使完成了上述分配,我们在 request
上的引用计数仍然为 2...
其中 requests 只是一个 RequestList 指针(原始指针)...
Does the following code mean that when this function returns, the request object inside this class still holds a reference to this object?
boost::shared_ptr<Request> RequestList::GetRequest()
{
boost::mutex::scoped_lock(listmtx);
request = boost::shared_ptr<Request>(new Request());
return request;
}
used:
request = requests->GetRequest(); //Ref count is two on request object when it returns??
even after having completed above assignment, we still have a ref count of two on request
...
where requests is just a RequestList pointer (raw pointer)...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
然后有两个带有
new Request()
句柄的shared_ptr
对象:调用函数中的一个和私有类变量。两者都合理地增加了重新计票。除非有理由存在私有类变量,否则将其消除。至少,将其重命名为
last_request
,因为这就是它的真正含义。(当然,当
last_request
被另一个对GetRequest
的调用重新分配时,它对前一个请求的句柄就会消失。)Then there are two
shared_ptr
objects with a handle to thenew Request()
: the one in the calling function and the private class variable. Both legitimately bump the refcount.Unless there's a reason for the private class variable to exist, eliminate it. At the very least, rename it
last_request
, because that's what it really is.(Of course, when
last_request
gets reassigned by another call toGetRequest
, its handle to the previous request goes away.)引用计数等于存在的共享指针的数量。在这种情况下,看起来在创建共享指针后,您最终会得到两个副本(在
GetRequest()
内对request
的分配,我猜是RequestList
的成员,以及将GetRequest()
结果分配给request
)。如果这两个都是共享指针,并且它们并不都引用同一个指针,那么最终将得到原始指针的两个副本,因此引用计数为 2。
The reference count is equal to the number of shared pointers in existence. In this case, it looks like, after creating the shared pointer, you end up with two copies (the assignment to
request
insideGetRequest()
, which I'm guessing is a member ofRequestList
, and the assignment torequest
of the result ofGetRequest()
).If both of these are shared pointers, and they don't both refer to the same pointer, then you will end up with two copies of the original pointer, and hence a reference count of two.
返回时有两个,语句末尾有一个。
所以当它返回时它是 2 因为有一个临时的。
当然,您可以使用 request.use_count() 来获取引用计数。
It's two on return, one at the end of the statement.
So when it returns it's 2 because there is a temporary.
Of course you can use
request.use_count()
to get the reference count.