【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;
}
相关推荐
dialect_8 小时前
KMP算法
开发语言·c++·算法
总要学点什么8 小时前
第89篇:三维特效-螺旋圆效果——让螺旋臂卷起一圈圈外扩的涟漪
开发语言·javascript·ecmascript·webgl·cesium·空间分析·1024程序员节
ShineWinsu10 小时前
对于Qt:QRadioButton常见属性以及QButtonGroup的解析
数据库·c++·qt·microsoft·gui·qradiobutton·qbuttongroup
傲世仙尊10 小时前
多态-虚表才活到运行期符号表早已消失
c++
开开心心_Every10 小时前
快速隐藏程序工具自定义快捷键一键切换
java·开发语言·前端·spring·智能手机·word·intellij-idea
chenbingjie_c10 小时前
C++ 多态完全指南:从虚函数重写到虚函数表原理
开发语言·c++
是main不是漫10 小时前
【双指针——移动零】数组划分类题目的入门基石
c++·算法
吴卫斌10 小时前
定投ETF实战指南(四):行业/主题ETF——定投的“进攻端“
开发语言·python·股票·量化
·present·10 小时前
CSAPP(Bomb lab)
c语言·c++
王老师青少年编程11 小时前
2026年信奥赛c++普及组csp-j第二轮复赛真题
c++·真题·csp·信奥赛