zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    页面与服务器的交互,,经典案例
    setInterval和clearInterval
    setAttribute,,,getAttribute,,,,
    字符串拼接
    上下图片连动效果
    文本框获得焦点
    获取机器上的时间
    检测奇偶性
    置顶博文
    P1962 斐波那契数列 题解
  • 原文地址:https://www.cnblogs.com/liutongqing/p/12551831.html
Copyright © 2011-2022 走看看