unique_ptr析构函数的优势

unique_ptr destructor advantage

本文关键字:析构函数 ptr unique      更新时间:2023-10-16

使用 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() 之间有很多代码,并且必须确保这些代码中的任何代码都不能跳过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()可以采取多种形式:returnifbreakcontinuegotothrow。 当您使用智能指针时,C++编译器会处理所有这些问题。