【16】c++11新特性 —>独占智能指针unique_ptr

初始化

std::unique_ptr是一个独占的智能指针,他不允许其他的智能指针共享其内部的指针,可以通过他的构造函数初始化一个独占智能指针对象,但是不允许通过赋值将一个unique_ptr赋值给另一个unique_ptr。

cpp 复制代码
unique_ptr<int> func()
{
	return unique_ptr<int>(new int(520));
}
int main()
{
	//通过构造函数初始化对象
	unique_ptr<int>ptr1(new int(10));
	//move ptr1不在指向之前的地址
	unique_ptr<int>ptr2 = move(ptr1);
	unique_ptr<int>ptr3 = func();
	return 0;
}

reset

使用reset方法可以让unique_ptr解除对原始内存的管理,也可以用来初始化一个独占的智能指针。

cpp 复制代码
int main()
{
	//通过构造函数初始化对象
	unique_ptr<int>ptr1(new int(10));
	//move ptr1不在指向之前的地址
	unique_ptr<int>ptr2 = move(ptr1);

	ptr1.reset(); //解除对原始内存的管理
	ptr2.reset(new int(1)); //重新指定智能指针管理的原始内存
	return 0;
}

原始地址

如果想要获取独占智能指针管理的原始地址,可以调用get()方法,函数原型如下:

cpp 复制代码
int main()
{
	//通过构造函数初始化对象
	unique_ptr<int>ptr1(new int(10));
	//move ptr1不在指向之前的地址
	unique_ptr<int>ptr2 = move(ptr1);

	cout << *ptr2.get() << endl;
	ptr2.reset(new int(1)); //重新指定智能指针管理的原始内存
	cout << *ptr2.get() << endl;
	return 0;
}
相关推荐
FuckPatience1 小时前
Visual Studio C# 项目中文件后缀简介
开发语言·c#
老四啊laosi7 小时前
[C++进阶] 24. 哈希表封装unordered_map && unordered_set
c++·哈希表·封装·unordered_map·unordered_set
014-code8 小时前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
妙为8 小时前
银河麒麟V4下编译Qt5.12.12源码
c++·qt·国产化·osg3.6.5·osgearth3.2·银河麒麟v4
lly2024068 小时前
组合模式(Composite Pattern)
开发语言
游乐码8 小时前
c#泛型约束
开发语言·c#
Dontla9 小时前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen9 小时前
python rest请求、requests
开发语言·python
铁东博客9 小时前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang
baidu_huihui9 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip