std::unique_ptr的使用

文章介绍了C++中的unique_ptr,它确保对对象的唯一所有权。当unique_ptr离开作用域或被重置时,其所管理的对象会被自动销毁。示例代码展示了在不同场景下,如函数传递和赋值时unique_ptr的行为。
摘要由CSDN通过智能技术生成

unique_ptr 表示对某一个对象的唯一一次引用,只要这个unique_ptr 退出生命周期(或者这个unique_ptr 指向其他对象或者调用 reset方法),则被引用的对象自动销毁。

#include <iostream>
#include <memory>
#include <unistd.h>
using namespace std;

class A18 {
public:
	A18() {
		cout << "default constructor" << endl;
	}
	int say() {
		cout << "A say:" << endl;
		return 0;
	}
	~A18() {
		cout << "Destructor called" << endl;
	}
};

void f0() {
	unique_ptr<A18> a(new A18());
	a->say();
}

void f1() {
 	std::unique_ptr<A18> p = std::make_unique<A18>(); 
	p->say();
}

void f2() {
 	std::unique_ptr<A18> p = std::make_unique<A18>(); 
 	//std::unique_ptr<A18> p2 = p; 
 	std::unique_ptr<A18> p2 = std::move(p); 
}

std::unique_ptr<A18> f3() {
 	std::unique_ptr<A18> p = std::make_unique<A18>(); 
 	return  p; 
}

int main() {
	f0();
	f1();
	std::unique_ptr<A18>      p3  =  f3();
	std::unique_ptr<A18>      p4  =  f3();
	
	sleep(1);
	cout << "end" << endl;
	return 0;
}

编译: g++ a.cpp -o a
执行: ./a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值