栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++ 智能指针 shared

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++ 智能指针 shared

c++ 智能指针 shared_ptr、weak_ptr、unique_ptr
  • 智能指针
  • unique_ptr
  • shared_ptr
  • weak_ptr
  • ----有空再补充

智能指针
  • 智能指针相比于普通指针,避免了内存泄漏的问题,能够在适当时机自动释放所占堆内存。
  • C++11标准库提供了三种智能指针, shared_ptr, weak_ptr, unique_ptr
  • 使用需要引入头文件
unique_ptr

unique_ptr独占所指堆内存空间,无法与其他指针共享,当该内存的引用计数为0,立刻进行内存回收。

  • 简单使用
    // https://en.cppreference.com/w/cpp/memory/unique_ptr
    
    #include 
    #include 
    
    using namespace std;
    
    int main() {
        unique_ptr up1(new string("unique_ptr"));
        cout << &up1 << " " << *up1 << endl; // out: 0x7ffddfcc9b48 unique_ptr
    //    unique_ptr up2(up1); // compile error
    
        unique_ptr up2(new string);
        *up2 ="unique_ptr";
        cout << &up2 << " " << *up2 << endl; // out: 0x7ffddfcc9b50 unique_ptr
        return 0;
    }
    
shared_ptr
  • shared_ptr允许多个指针指向同一个对象,
// https://en.cppreference.com/w/cpp/memory/shared_ptr

#include 
#include 

using namespace std;

class A {
public:
    A(int i): n(i)
    {
        cout << "A init..." << endl;
    }
    ~A()
    {
        cout << "A end..." << endl;
    }

private:
    int n;
};

int main() {
    shared_ptr sp1(new A(1));
    cout << sp1 << " " << sp1 << " " << sp1.use_count() << endl;

    shared_ptr sp2(sp1);
    cout << sp2 << " " << sp2 << " " << sp2.use_count() << endl;
    return 0;
}
weak_ptr
  • 为了避免shared_ptr循环引用(即A、B互相引用导致内存泄漏),C++11引入了weak_ptr,它是一种弱引用,指向shared_ptr所管理的对象
----有空再补充
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号