C++ 用同一个raw pointer传入shared_ptr构造函数生成两个智能指针有什么问题?
Effective Modern C++
Item 19: use std::shared_ptr for shared-ownership resource
Now, the constructor for spw1 is called with a raw pointer, so it creates a control block (and thereby a reference count) for what’s pointed to. In this case, that’s *pw (i.e., the object pointed to by pw). In and of itself, that’s okay, but the constructor for spw2 is called with the same raw pointer, so it also creates a control block (hence a reference count) for pw.pw thus has two reference counts, each of which will eventually become zero, and that will ultimately lead to an attempt to destroy *pw twice.
使用同一个raw_pointer传入智能指针构造函数,生成两个不同的智能指针。那么会为两个智能指针生成两个独立的控制块,并且在智能指针析构时讲原来raw_pointer指向的内存析构两次。
#include <iostream>
#include <memory>
using namespace std;
class Widget{
public:
Widget(int val):val(val){
cout<<"constructor"<<endl;
}
~Widget(){
cout<<"destructor "<<val<<endl;
}
private:
int val;
};
int main() {
Widget *wp = new Widget(10);
shared_ptr<Widget> sp1(wp);
shared_ptr<Widget> sp2(wp);
shared_ptr<Widget> sp3 = sp2;
cout<<sp3.use_count()<<endl;
cout<<sp1.use_count()<<endl;
return 0;
}
constructor
2
1
destructor 10
destructor 9798288
分类:
Modern C++
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?