c++ - 返回 shared_ptr 时的引用计数

标签 c++ smart-pointers

下面的代码是不是意味着当这个函数返回时,这个类里面的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 指针(原始指针)...

最佳答案

request is a private class variable...

然后有两个shared_ptr 对象带有new Request() 的句柄:调用函数中的一个和私有(private)类变量。两者都合理地提高了重新计票。

除非有理由让私有(private)类变量存在,否则将其删除。至少,将其重命名为 last_request,因为它确实如此。

(当然,当 last_request 被另一个对 GetRequest 的调用重新分配时,它对先前请求的句柄就会消失。)

关于c++ - 返回 shared_ptr 时的引用计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3905135/

相关文章:

C++防止某个类的派生类对两个类的多重继承

c++ - 使用 free() 释放 new 分配的内存空间

C++指针返回0值

c++ - XCode C++ 缺少精子 ()

c++ - 用于 boost shared_ptr 的自定义删除器

c++ - 这是 unique_ptr 的正确用法吗?

c++ - 使用标准 C++/C++11、14、17/C 检查文件是否存在的最快方法?

c++ - 如何实现智能容器的拷贝构造函数?

c++ - shared_ptr 的缺点

c++ - 为什么 g++ (4.8.2) 默认使用 c++0x?