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

原文链接: https://www.cnblogs.com/liutongqing/p/12551831.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++11中的智能指针shared_ptr

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/337108

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午11:00
下一篇 2023年3月1日 下午11:00

相关推荐