From a013348a7e5632b79bf064a6ee5ac4d5be45581f Mon Sep 17 00:00:00 2001 From: Rob Adams Date: Fri, 4 Dec 2015 16:12:55 -0800 Subject: [PATCH] Calling delete on a FILE* created with fopen is ill-advised. Uses a custom deleter. --- CppCoreGuidelines.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index 241e7d6..64a6b30 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -13817,17 +13817,25 @@ That would be a leak. 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`: +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: void f(int i) { - unique_ptr f = fopen("a file", "r"); + unique_ptr f(fopen("a file", "r"), fclose); // ... if (i == 0) return; // ... } -The code is simpler as well as correct. +Better: + + void f(int i) + { + ifstream input {"a file"}; + // ... + if (i == 0) return; + // ... + } ##### Enforcement