与仅在C ++ 11中直接关闭文件相比,使用unique_ptr析构函数有什么好处?
即此代码
FILE* p = fopen("filename","r");
unique_ptr<FILE, int(*)(FILE*)> h(p, fclose);
if (fclose(h.release()) == 0)
p = nullptr;
与
FILE* p = fopen("filename","r");
fclose(p)
不需要第一个代码块的最后两行。另外,您对文件不做任何事情。这就是优势变得明显的地方。
使用unique_ptr,您可以fclose()
在打开文件时安排一次调用,而不必担心它。
使用C样式时,您之间会有很多代码fopen()
,fclose()
并且必须确保所有代码都不能跳过fclose()
。
这是一个更现实的比较:
typedef std::unique_ptr<FILE, int(*)(FILE*)> smart_file;
smart_file h(fopen("filename", "r"), &fclose);
read_file_header(h.get());
if (header.invalid) return false;
return process_file(h.get());
与
FILE* p = fopen("filename","r");
try {
read_file_header(p);
}
catch (...) {
fclose(p);
throw;
}
if (header.invalid) {
fclose(p);
return false;
}
try {
auto result = process_file(p);
fclose(p);
return result;
}
catch (...) {
fclose(p);
throw;
}
跳跃在fclose()
可以采取多种形式:return
,if
,break
,continue
,goto
,throw
。使用智能指针时,C ++编译器将处理所有这些代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句