Unique_ptr 自动毁灭魔法
Unique_ptr auto destruction magic
来自 : http://en.cppreference.com/w/cpp/memory/unique_ptr
问题:为什么仅当 fp 不为 NULL 时才调用 close()?
std::unique_ptr<std::FILE, decltype(&std::fclose)> fp(std::fopen("demo.txt", "r"),
&std::fclose);
if(fp) // fopen could have failed; in which case fp holds a null pointer
std::cout << (char)std::fgetc(fp.get()) << '\n';
块下面的评论 : // fclose() 在这里调用,但前提是 FILE* 不是空指针
//(也就是说,如果 fopen 成功)
问题: 这是怎么发生的?我知道调用 close(NULL) 是不好的。那么检查发生在哪里? decltype(&std::fclose) 是怎么知道检查 null 的?如果在其他时间甚至在 null 上调用它是可取的并由函数处理怎么办?
unique_ptr::~unique_ptr 的要求要求它将 get()
与 nullptr
进行比较,并且仅在不为空时才调用删除器。
如果希望在 nullptr
上调用您的删除器,则您的应用程序是非典型的,可能不适合使用 unique_ptr
。您无法修改此行为。
来自 : http://en.cppreference.com/w/cpp/memory/unique_ptr
问题:为什么仅当 fp 不为 NULL 时才调用 close()?
std::unique_ptr<std::FILE, decltype(&std::fclose)> fp(std::fopen("demo.txt", "r"),
&std::fclose);
if(fp) // fopen could have failed; in which case fp holds a null pointer
std::cout << (char)std::fgetc(fp.get()) << '\n';
块下面的评论 : // fclose() 在这里调用,但前提是 FILE* 不是空指针 //(也就是说,如果 fopen 成功)
问题: 这是怎么发生的?我知道调用 close(NULL) 是不好的。那么检查发生在哪里? decltype(&std::fclose) 是怎么知道检查 null 的?如果在其他时间甚至在 null 上调用它是可取的并由函数处理怎么办?
unique_ptr::~unique_ptr 的要求要求它将 get()
与 nullptr
进行比较,并且仅在不为空时才调用删除器。
如果希望在 nullptr
上调用您的删除器,则您的应用程序是非典型的,可能不适合使用 unique_ptr
。您无法修改此行为。