unique_ptr 析构函数优势
unique_ptr destructor advantage
使用 unique_ptr 析构函数比在 C++11 中直接关闭文件有什么优势?
即此代码
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()
之间有很多代码,必须确保该代码的 none 可以跳过 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++ 编译器会处理所有这些问题。
使用 unique_ptr 析构函数比在 C++11 中直接关闭文件有什么优势?
即此代码
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()
之间有很多代码,必须确保该代码的 none 可以跳过 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++ 编译器会处理所有这些问题。