智能指针 shared_ptr 使用

C++ shared_ptr 使用总结:

复制代码
class Color
{
public:
    Color(uint32_t _red, uint32_t _yellow, uint32_t _green)
            : mRed(_red)
            , mYellow(_yellow)
            , mGreen(_green)
    {

    }

    const uint32_t getRed() {
        return mRed;
    }
    const uint32_t getYellow() {
        return mYellow;
    }
    const uint32_t getGreen() {
        return mGreen;
    }

private:
    uint32_t mRed;
    uint32_t mYellow;
    uint32_t mGreen;
};
复制代码

 

1. 初始化三种方式

    shared_ptr<Color> pPtr1 = make_shared<Color>(4,4,2, "make_shared consruct"); // method 1
    shared_ptr<Color> pPtr2(new Color(4,5,2, "initialize list"));               // method 2
    shared_ptr<Color> pPtr3(nullptr);                                           // method 3
    pPtr3 = make_shared<Color>(4,4,2,"copy construct");

 

2. 指针使用:可以直接当做普通使用,调用对应的函数或者变量

    cout << pPtr1->getRed() << endl;
    cout << pPtr2->getYellow() << endl;
    cout << pPtr1->getGreen() << endl;

 

 3. 当一个智能指针被重新赋值后,它以前指向的数据的use_count就会减1,如果减到0后,就会释放其内存;

1
2
3
weak_ptr<Color> pWeakPtr = pPtr1;
pPtr1 = pPtr2;
cout << pWeakPtr.use_count() << endl;

 当输出的值为0时,表示前面指向的数据被释放掉了。

 

注:智能智能存在的问题:

1. 当类中的 uint32_t 变成 u_int8(unsigned char)后,上诉1,2步骤后,得不到对应值。

2. 但是使用裸指针获取没有问题。

posted @   王清河  阅读(107)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2019-12-07 Ubuntu终端字体
点击右上角即可分享
微信分享提示