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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章