Discussion: Never throw while holding a resource not owned by a handle
讨论:持有没有被句柄管理的资源时切勿抛出异常
Reason(原因)
That would be a leak.
这回引发资源泄露。
Example(注意)
void f(int i)
{
FILE* f = fopen("a file", "r");
ifstream is { "another file" };
// ...
if (i == 0) return;
// ...
fclose(f);
}
If i == 0 the file handle for a file is leaked. On the other hand, the ifstream for another file will correctly close its file (upon destruction). If you must use an explicit pointer, rather than a resource handle with specific semantics, use a unique_ptr or a shared_ptr with a custom deleter:
如果i == 0,则文件的句柄发生泄漏。另一方面,另一个文件的ifstream将正确关闭其文件(销毁时)。如果必须使用显式指针,而不是具有特定语义的资源句柄,请使用带有自定义删除器的unique_ptr或shared_ptr:
void f(int i)
{
unique_ptr<FILE, int(*)(FILE*)> f(fopen("a file", "r"), fclose);
// ...
if (i == 0) return;
// ...
}
Better:
更好的做法:
void f(int i)
{
ifstream input {"a file"};
// ...
if (i == 0) return;
// ...
}
A checker must consider all "naked pointers" suspicious. A checker probably must rely on a human-provided list of resources. For starters, we know about the standard-library containers, string, and smart pointers. The use of span and string_view should help a lot (they are not resource handles).
检查器必须将所有“暴露的指针”视为可疑。检查器可能必须依靠人工提供的资源列表。首先,我们了解标准库容器,字符串和智能指针。使用span和string_view应该会很有帮助(它们不是资源句柄)。
原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#discussion-never-throw-while-holding-a-resource-not-owned-by-a-handle