【智能指针】


前言

智能指针是模板类中的内容,为了避免野指针,悬挂指针,内存泄漏的问题。它存储了申请了堆内存后返回的指针。C++11后有三种类型的指针: shared_ptr, unique_ptr, weak_ptr

一、std::unique_ptr

#include <iostream>
int main() {
	int* a = new int;//原始指针
	int* b = a;
	delete a;
	std::unique_ptr<int[]> intPtr{ new int[3] {1,2,3} };//第一种初始化方式
	std::unique_ptr<int[]> intPtrD{ std::make_unique<int[]>(5) };//第二种初始化方式
	std::unique_ptr<int> intPtrA{ new int(5) };
	std::unique_ptr<int> intPtrB{ std::make_unique<int>(5) };
	std::unique_ptr<int> intPtrC{};
	intPtrB.reset();//1.释放堆内存 2.置为NULL
	int* resultPtr = intPtrB.get();//1.得到原始指针
	int* resultPtrA = intPtrB.release();//1.置为NULL 2.返回原始指针
	//intPtrA = intPtrB;//std::unique_ptr:特点是该指针具有唯一性(不能赋值拷贝)
	std::cout << intPtr << " " << intPtr[1] << std::endl;

	std::cout << intPtrC << " " << intPtrA << std::endl;
	intPtrC = std::move(intPtrA);//相当于赋值操作
	std::cout << intPtrC << " " << intPtrA << std::endl;

}

二、std::shared_ptr

#include <iostream>
int main() {
	int* a{};
	std::shared_ptr<int> ptrA{ std::make_shared<int>(6) };
	std::shared_ptr<int> ptrB{ ptrA };//std::shared_ptr:特点是该指针具有共享性(可以赋值拷贝)
	//std::shared_ptr<int> ptrC{ std::make_shared<int[]>(5) };//std::make_shared不支持数组
	std::shared_ptr<int> ptrC{ new int[3] {1,2,3} };//std::make_shared不支持数组
	std::cout << ptrA << " " << *ptrA << std::endl;
	std::cout << ptrB << " " << *ptrB;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值