智能指针

智能指针

new, share_ptr指针类型的基本初始化和使用.
share_ptr : 编译器自动的释放内存, 不需要手动delete;
new : 我们需要手动的释放内存(delete);

#include <iostream>
#include <cstdlib>
#include <memory>
#include <string>
#include <new>


int main()
{
	//new : 初始化, 建议使用new int(); 直接初始化;
	int *a1 = new int;
	int *a2 = new int();
	int *a3 = new (std::nothrow) int();		//nothrow 分配空间失败时会自动将 a3 变为空指针而不是编译报错;
	int *a = new int[20]();					//new : 分配一个数组;
	delete[] a;								//销毁数组, 要加 [] ;
	delete a1;
	delete a2;
	delete a3;


	//shared_ptr : 智能指针的初始化; 系统自动释放内存;
	//shared_ptr : 不支持管理动态数组;
	//unique_ptr, weak_ptr暂未了解;
	std::shared_ptr<std::string> p1 = std::make_shared<std::string >("adsd");
	std::cout << *p1 << "\n";

	std::shared_ptr<std::string > p2 = std::make_shared<std::string >(10, 'a');
	std::cout << *p2 << "\n";

	std::shared_ptr<int > p3(new (std::nothrow) int(29));
	std::cout << *p3 << "\n";

	//shared_ptr : 不支持管理动态数组;
	//智能用lambda做为删除器执行释放数组[];
	//对其赋值和遍历只能用 p.get() 以及下标运算符;
	std::shared_ptr<int> p4(new (std::nothrow) int[10], [](int *p4) { delete p4; });
	for (size_t i = 0; i < 10; i++)
		*(p4.get() + i) = i;
	for (size_t i = 0; i < 10; i++)
		std::cout << *(p4.get() + i) << "   ";



	system("pause");
	return 0;
}

自我感觉share_ptr好处很好, 弊端也大, 动态数组创建太麻烦了.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值