c++ unique_ptr shared_ptr weak_ptr

通过断点可以更加形象的看到程序运行过程,其中不同的注释代码可以调用。

#include<iostream>
#include<string>
#include<memory>

//通过智能指针来实现new delete 的自动化调用,本质上是一个原始指针的包装
//unique_ptr 是作用域指针,是超出作用域时,
//shared_ptr工作方式通过引用计数跟踪指针有多少个引用,引用计数达0删除

class entity
{
public:
	entity()
	{
		std::cout << "Created entity!" << std::endl;
	}
	~entity()
	{
		std::cout << "Destroyed entity!" << std::endl;
	}
	void print(){}

};

int main()
{
	{
		std::shared_ptr<entity> e0;
		//std::weak_ptr<entity>e0;
		{

			//std::unique_ptr<entity>e0=new entity(); unique_ptr调用了explicit 只能显式调用构造函数
			//std::unique_ptr<entity>e0(new entity());
			//std::unique_ptr<entity>e0 = std::make_unique<entity>();
			//std::make_unique在内存分配和对象构造期间提供了异常安全保证。
			// 例如,当你在函数调用中传递多个以new表达式构造的参数时,如果其中一个参数构造抛出异常,那么在这个参数之前构造的参数可能不会被删除,导致内存泄漏。
			// 而std::make_unique可以防止这种情况发生。
			//错误示例 std::unique_ptr<entity>e1= e0;拷贝构造函数与操作符实际被删除了

			std::shared_ptr<entity>sharedentity = std::make_shared<entity>();
			//std::shared_ptr<entity>sharedentity(new entity());
			//std::weak_ptr<entity>weakentity = sharedentity;//不增加引用计数
			e0 = sharedentity;
		}
	}
	std::cin.get();
}

weak_ptr 与shared_ptr作用不同 在离开第一个作用域weak_ptr立即销毁而shared_ptr在第二个作用域进行销毁。unique_ptr优先使用, shared_ptr更适合对象间共享。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值