【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;
}
相关推荐
昵称画3 小时前
交接班记录电子化:三班之间的信息不漏
开发语言·数据库·人工智能·低代码·php
“AI国潮设计-小江”4 小时前
【AIGC实战】Python+SDXL批量生成“潮汕英歌舞不倒翁”IP | 角色一致性与多场景融合方案,附完整代码
开发语言·人工智能·python·prompt·aigc
传奇开心果编程4 小时前
【Rust入门练中学】第6课:结构体与方法
开发语言·rust·结构体·编程语言理论·结构体方法·编程通用语言
code tsunami4 小时前
【无标题】
开发语言·python
CodeGL5 小时前
10、Python基础之进程和线程
开发语言·python
hetao17338375 小时前
2026-10-22~23 hetao1733837 的刷题记录
c++·算法
TechWayfarer6 小时前
PHP漏洞被利用,怎么揪出攻击IP?
开发语言·python·tcp/ip·网络安全·php
王老师青少年编程6 小时前
2025年6月GESP真题及题解(C++三级): 选择题和判断题(题解)
c++·真题·gesp·答案·csp·三级·信奥赛
卡卡~~7 小时前
“101计划”核心课程实践教材《数据实验结构指导-C++语言版》题目集
开发语言·c++·学习·算法
qq_406981037 小时前
大白话rust系列09 函数调用两次有什么错?
开发语言·python·rust