c++/c 标准库 unique_ptr


#include <iostream>
#include <string>
#include <memory> //unique_ptr
#include <vector>

using namespace std;
/**
 *资源任何时候只能被一个对象所拥有,我们常用到的指针,可能类似于unique_ptr更多些,其用于解决内存汇露方法 较发
 * 构造函数中,第一个是资源类型,第二个是删除子,第二个一般使用默认的。
 * unique_ptr<...> up						default constructor,create an empty unique pointer using an instance of the default/passed delete type as deleter
 * unique_ptr<T> up(nullptr)				create an empty unique pointer,using an instance of the defalut/passed deleter type as deleter
 * unique_ptr<...> up(ptr)					create a unique pointer owing *ptr,using an default/passed deleter
 * unique_ptr<...> up(ptr,del)				create a unique pointer owing *ptr,using del as deleter
 * unique_ptr<T> up(move(up2))				仅接受右值构造,和赋值。
 * unique_ptr<T> up(move(ap))
 * up.~unique_ptr();
 * up = move(up2)
 * up = nullptr;
 * up1.swap(up2)
 * swap(up1,up2)
 * up.reset()								和 =nullptr 意义相同,都是
 * up.reset(ptr)							重新拥 有*ptr,删除原
 * up.release()								返回指针,放弃所有权。
 * up.get()									返回地址
 * *up
 * up->
 * up[idx]									仅仅为数组提供,比shared_ptr 多提供,unique_ptr默认支持数组,
 * up1 == up2 up1 != up2
 * up1 > up2 up1 < up2 up1 >= up2 up1 <= up2
 * up.get_deleter()							返回删除子的引用
 *
 * 未提供类型转换,不支持!
 *
 */

int main() {
	auto del = [](int* p){
		cout << "deleting ...\n";
		delete p;
	};

	//deleter 类型作为模板第二个参数,且在构造函数中第二个实参需要传入
	unique_ptr<int,decltype(del)> up(new int(33),del);
	cout << *up << endl;

	//定义 array时,应定义delete,且类型可以数级型,这和shared_ptr不同
	char ch[2]={'a','b'};
	unique_ptr<char[],void(*)(char*)> up1(new (ch)char[2],[](char* p){
		cout << "delete array...\n";
		delete []p;
	});
	cout << up1[0] << endl;//此时不能通过*或->访问


	//我们由上可以看出未定义拷贝赋值,所以
	unique_ptr<string> up2(new string("unique_ptr\n"));
	//unique_ptr<string> up3 = up2; 错误,无左值,只可右值
	unique_ptr<string> up3 = std::move(up2);
	if(up2){
		cout << "up2 has been alive!\n";
	}else{
		cout <<"up2 has delete,and up3 :"<<*up3<<endl;
	}
	//赋值也是同样的问题
	//up2 =up3;
	up2 = move(up3);
	if(up3){
		cout << "up3 has been alive!\n";
	}else{
		cout << "up3 has delete ,and up2 :" <<*up2<<endl;
	}

	//除此,用指针=亦不允许
	//unique_ptr<string> up4 = new string("up4");
	unique_ptr<string> up4(new string("up4"));
	cout << *up4;

	//reset,realease,get

	cout << "beore reset up4 addr: "<< up4.get()<<endl;
	up4.reset(new string("resetup4"));
	cout << "after reste up4 addr :" << up4.get()<<endl;
	string* uprealease = up4.release();
	if(nullptr == up4){
		cout << "up4 has been delete\n";
	}
	cout <<"uprealse is :"<< *uprealease<<endl;
	//unique_ptr 两个类不能同时指向一个资源,这是必须的,所以以下这种一定是错,但它是一个运行错误。gcc可能存在优化,不会产生,不能如此使用
#if 0
	string* sp =new string("sp");
	unique_ptr<string> up5(sp);
	unique_ptr<string> up6(sp);
#endif
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值