首页 > 编程语言 >C++ 用同一个raw pointer传入shared_ptr构造函数生成两个智能指针有什么问题?

C++ 用同一个raw pointer传入shared_ptr构造函数生成两个智能指针有什么问题?

时间:2023-02-21 16:56:00浏览次数:31  
标签:pw C++ raw shared 指针 pointer 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

标签:pw,C++,raw,shared,指针,pointer,ptr,构造函数
From: https://www.cnblogs.com/qiangz/p/17141579.html

相关文章

  • 【新品发布】如何将Spire.XLS for C++集成到C++ 程序中
    Spire.XLSforC++是一个Excel库,供开发人员在任何类型的C++应用程序中操作Excel文档(XLS、XLSX、XLSB和XLSM)。本文演示了如何以两种不同的方式将Spire.XLSforC......
  • C/C++运动会比赛计分系统[2023-02-21]
    C/C++运动会比赛计分系统[2023-02-21]软件学院课程设计任务书课程设计名称 程序设计基础课程设计 学期 2022-2023-2学生姓名 学号 课程设计题目 128.运动会比赛计分系......
  • C++面对对象:实现complex类
    1#ifndef__MYCOMPLEX_H__2#define__MYCOMPLEX_H__34classcomplex;5complex&__doapl(complex*,constcomplex&);//友元可以在类外声明6compl......
  • C++ json库jsoncpp 吐槽
    Explain   最近在做游戏接入SDK时用到C++的json库jsoncpp,jsoncpp 是一款优秀的json库,但恶心的一点是它采用Assert作为错误处理方法,而assert在linux下通过调用abort......
  • Jni中C++和Java的参数传递
    如何使用JNI的一些基本方法和过程在网上多如牛毛,如果你对Jni不甚了解,不知道Jni是做什么的,如何建立一个基本的jni程序,或许可以参考下面下面这些文章:利用VC++6.0实现JNI的最......
  • C++输出文件名、函数名、行号
    11std::cout<<"filepath=%s"<<__FILE__;//源文件名22std::cout<<"functionname=%s"<<__FUNCTION__;//函数名称33std::c......
  • C++数组
    C++一维数组C++数组的定义方式数据类型数组名[数组长度];例子:intarr[3];arr[0]=1;arr[1]=2;arr[2]=3;数据类型数组名[数组长度]=intarr[3]=......
  • c++学习
      c++字符串转化为整数浮点数。   string和char直接转换============31m代表字体为红色,0m代表关闭所有属性。常用的ANSI控制码如下(有些不支持):\033[0m关闭所......
  • 树状数组板子C++
    1intn;2inta[1005],c[1005];//对应原数组和树状数组34intlowbit(intx){5returnx&(-x);6}78voidupdata(inti,intk){//在i位置加......
  • 【数组与链表算法】矩阵算法在程序中常见的简单应用 | C++
    第二十三章矩阵算法:::hljs-center目录第二十三章矩阵算法●前言●矩阵算法与深度学习●一、矩阵相加●二、矩阵相乘●三、矩阵转置●四、稀疏矩阵●......