AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

shared_ptr与weak_ptr使用的注意事项

作者: 作者的头像   炼心 ,  2019-11-04 11:37:03 ,  所有人可见 ,  阅读 2604


4


1

shared_ptr与weak_ptr

使用shared_ptr控制对象的生命周期,常用来进行对象的创建,属于强引用,只要被shared_ptr引用该对象就不会被析构

weak_ptr是一种弱引用,常常用来侦查对象是否存在,不控制对象的生命期,
也不会增加对象的引用计数如果对象还存在没被析构那么可以通过成员函数进行提升为强引用

shared_ptr = weak_ptr.lock()

提升和引用计数都是原子操作的。

scope_ptr可以解决重复释放内存泄漏

Shared_ptr::reset()函数若没有传入参数,那么智能指针会停止对保存指针的所有权的共享,
共享资源的引用计数减一。如果传入一个对象则释放当前的对象,去管理新传入的对象

关于多线程如何避免访问已经释放的内存


#include<iostream>
#include<thread>
#include<mutex>
#include<memory>

using namespace std;
class A{
    public:
        A(){}
        ~A(){
            cout<<"destructor"<<endl;
        }
        void func(){
            cout<<"A function"<<endl;
        }
};
void handle(weak_ptr<A> p){
    //弱指针转换成强指针
    shared_ptr<A> q=p.lock();
    if(q!=nullptr){
        q->func();
    }else{
        cout<<"A already destructor"<<endl;
    }
}
int main(){
    shared_ptr<A> p(new A());
    thread t1(handle,p);
    return 0;
} 

如何解决循环引用所导致的内存泄露问题

解决循环引用需要将引用的其中一方换成弱引用

#include<iostream>
#include<memory>

using namespace std;

class children;
class parent;

typedef shared_ptr<children> children_ptr;
typedef shared_ptr<parent> parent_ptr;

class parent{
  public:
  children_ptr children;
  ~parent(){cout<<"parent destructor"<<endl;}
};
class children{
  public:
    weak_ptr<parent> parent;
    ~children(){cout<<"childrent destructor";}
};

void test(){
  children_ptr c(new children());
  parent_ptr p(new parent());

  c->parent=p;
  p->children=c;

  cout<<c.use_count()<<endl;
  cout<<p.use_count()<<endl;
}
int main(){
  test();
  getchar();
  return 0;
}

3 评论


用户头像
itdef   2019-11-04 13:57         踩      回复
可以参考 陈硕的 Linux多线程服务端编程:使用muduo C++网络库

1.4线程安全的Observer 有多难.. . . . . . . . . . . . . . . . . . . . . . . . 8
1.5原始指针有何不妥. . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . 11
1.6神器shared_ptr/weak_ptr . . . . . . . . . .. . . . . . . . . . . . . . . . 13
1.7插曲:系统地避免各种指针错误. . . . . . . . . . . . . . . . .. . . . . . 14
1.8应用到Observer 上.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.9再论shared_ptr 的线程安全.. . . . . . . . . . . . . . . . . . . . . . . . 17
1.10shared_ptr 技术与陷阱. . . .. . . . . . . . . . . . . . . . . . . . . . . . 19
1.11对象池. . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . 21
1.11.1enable_shared_from_this . . . . . . . . . . . . . . . . . . . . . . 23
1.11.2弱回调. . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . 24

用户头像
炼心   2019-11-04 18:19         踩      回复

嗯嗯,好的,谢谢了。


用户头像
itdef   2019-11-04 13:55         踩      回复

shared_ptr 要实践到工程中 还得加强学习 enable_shared_from_this 原理与用法
不然坑还是一个都不少


App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息