tongqingliu

保持学习的态度

C++11中的智能指针shared_ptr

多个shared_ptr可以指向同一个对象,当对象不再使用时,shared_ptr被自动清理。

#include <iostream>
#include <string>
#include <vector>
#include <memory>
using namespace std;

int main()
{
    // 初始化两个智能指针
    shared_ptr<string> pNico(new string("nico"));
    shared_ptr<string> pJutta(new string("jutta"));

    // 通过指针修改string的内容
    (*pNico)[0] = 'N';
    pJutta->replace(0,1,"J");
    
    // 将共享指针推至vector
    vector<shared_ptr<string>> whoMadeCoffee;
    whoMadeCoffee.push_back(pJutta);
    whoMadeCoffee.push_back(pJutta);
    whoMadeCoffee.push_back(pNico);
    whoMadeCoffee.push_back(pJutta);
    whoMadeCoffee.push_back(pNico);

    // 打印vector中所有元素
    for (auto ptr : whoMadeCoffee) {
        cout << *ptr << "  ";
    }
    cout << endl;

    // 修改共享指针指向的内容
    *pNico = "Nicolai";

    // 打印vector中所有元素
    for (auto ptr : whoMadeCoffee) {
        cout << *ptr << "  ";
    }
    cout << endl;
    
	// 打印vector中所有元素
    for (int i=0; i<whoMadeCoffee.size(); i++)
    {
        cout << *whoMadeCoffee[i] << "  ";
    }
    cout << endl;
    
    // 打印use_count
    cout << "use_count: " << whoMadeCoffee[0].use_count() << endl;
}

程序输出:

Jutta  Jutta  Nico  Jutta  Nico
Jutta  Jutta  Nicolai  Jutta  Nicolai
Jutta  Jutta  Nicolai  Jutta  Nicolai
use_count: 4

posted on   tongqingliu  阅读(362)  评论(0编辑  收藏  举报

编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构

导航

统计信息

点击右上角即可分享
微信分享提示