【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;
}
相关推荐
Yunovian1 小时前
AI时代,针对模型与应用,浅谈一下各编程语言
开发语言·c++·人工智能·python·ai·rust·ai编程
周杰伦fans2 小时前
构建真正智能的CAD AI绘图代理
开发语言·人工智能·c#
zhanghaha13144 小时前
Python进阶教程:35_PyQt (保姆级零基础教程)
开发语言·python·pyqt
释厄6234 小时前
多黑洞具现论·物理/生物/金融三域显化·虚拟宇宙黑洞·奇点=0 圆圈
开发语言·数据结构·人工智能·程序人生·安全威胁分析
UIU1146 小时前
递归算法与汉诺塔
c++·学习·算法·c#·递归
Fruit_Caller6 小时前
static
开发语言·c++
codigger11 小时前
ObjectSense:一门千行内核、把可靠性写进骨子里的面向对象脚本语言
开发语言·编程·编程语言
小小龙学IT12 小时前
Boost.Interprocess 开源 C++ 进程间通信库深度解析
c++·开源
倒头就睡的小比特6 天前
算法竞赛C++常用的STL
c++·算法
weilx12346 天前
C++笔记-文件IO-<fcntl.h>
c++