#include <iostream>
#include <set>
#include <vector>
#include <map>
#include <fstream>
#include <sstream>
#include <unordered_set>
#include <memory>
int main()
{
// 空的share_ptr 里边保存了一个空指针
std::shared_ptr<std::string> p1;
// shared_ptr重载了operator bool() 可用于判断其内部有没有指针
if (!p1) {
std::cout << "empty share_ptr p1" << std::endl;
}
// make_shared是最安全的分配和使用动态内存的方法
std::shared_ptr<std::string> p2 = std::make_shared<std::string>();
// shared_ptr重载了operator bool() 可用于判断其内部有没有指针
if (p2 && p2->empty()) {
*p2 = "string";
// 最好不要使用get函数来获取到普通指针 如果普通指针和智能指针混用 智能指针就没有意义了
*(p2.get()) = "string2";
}
std::cout << *p2 << std::endl;
// unique函数用于判断该智能指针是否是唯一一个使用该内存的指针
if (p2.unique()) {
std::cout << "p2 unique" << std::endl;
}
decltype(p2) p3;
p3 = p2;
if (!p2.unique()) {
std::cout << "p2 not unique" << std::endl;
}
// 有时在修改智能指针管理的内存的值之前 可能要判断下是否有其他地方也在使用这块内存
// 如果不想这块内存被修改而影响其他地方 可以拷贝一份该内存
if (!p2.unique()) {
p2.reset(new std::string(*p3));
// 再对p2做其他操作
}
// shared_ptr内部有引用计数 拷贝/赋值导致其内部的引用计数就会递增 智能指针离开作用域析构时 引用计数就会递减
// use_count用于返回引用计数的值 速度可能会比较慢 一般用于调试
std::shared_ptr<std::string> p4;
{
std::shared_ptr<std::string> temp = std::make_shared<std::string>("temp");
std::cout << temp.use_count() << std::endl; // 输出1 temp的引用计数为1
p4 = temp; // 赋值导致引用计数+1
std::cout << temp.use_count() << std::endl; // 输出2 temp的引用计数为2
std::cout << p4.use_count() << std::endl; // 输出2 p4的引用计数为2
}
std::cout << p4.use_count() << std::endl; // 输出1 temp离开作用域析构 引用计数-1
return 0;
}
c++ shared_pt的基本使用方法
于 2024-03-20 20:25:03 首次发布
本文详细介绍了C++中的std::shared_ptr概念,包括如何检查空指针,使用make_shared创建安全的动态内存,operatorbool的用法,unique函数的应用,以及引用计数在内存管理和拷贝中的作用。
摘要由CSDN通过智能技术生成