多个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