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 2023-02-21 16:47  七昂的技术之旅  阅读(34)  评论(0编辑  收藏  举报

导航