c++ shared_pt的基本使用方法

#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;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值