unique_ptr与shared_ptr的一个坑

当所维护的指针为nullptr时
unique_ptr释放时不会调用Deleter
shared_ptr释放时会调用Deleter

在某些情况下,比如 FIFE 类型指针的 Deleter ,即 fclose, 调用 fclose(nullptr) 会抛异常

/*
 * Author:ZhangBinjie@Penguin
 */
#include 

using namespace std;

void fun1() {
	//unique_ptr p(fopen("a.txt","w"),fclose);	
	unique_ptr p(nullptr,fclose);
}

void fun2() {
	//shared_ptr p(fopen("a.txt", "w"), fclose);
	shared_ptr p(nullptr, fclose);
}

int main() {
	fun1();
	cout << "unique success" << endl;
	fun2();
	cout << "shared success" << endl;
	return 0;
}

结果:
unique success
[Finished in 1.1s with exit code -11]

你可能感兴趣的:(杂谈)