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

posted on   七昂的技术之旅  阅读(46)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示