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()
之间有很多代码,并且必须确保这些代码中的任何代码都不能跳过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++编译器会处理所有这些问题。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 内联映射初始化的动态atexit析构函数崩溃
- 什么时候调用析构函数
- 优先顺序:智能指针和类析构函数
- C++-明确何时以及如何调用析构函数
- 使用基类指针创建对象时,缺少派生类析构函数
- 在c++中使用向量时,如何调用构造函数和析构函数
- 重载运算符new[]的行为取决于析构函数
- 我需要知道编译器如何在cpp中使用析构函数
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- 析构函数调用
- 通过引用传递-为什么要调用这个析构函数
- 对具有动态分配的内存和析构函数的类对象的引用
- 重载 -> shared_ptr 个实例中的箭头运算符<interface>,接口中没有纯虚拟析构函数
- C++成员的析构函数顺序与shared_ptr
- 带智能ptr的Pimpl-为什么需要构造函数/析构函数
- c++在没有虚拟析构函数的多态性中共享ptr
- 为什么这个显式析构函数会导致共享ptr中的内存损坏
- c++类的析构函数包含ptr到对象的数组