From ddef6cdbaeba9ec70e58e52eeb54635c0f3f0804 Mon Sep 17 00:00:00 2001 From: Markus Hofbauer Date: Thu, 19 May 2022 23:05:04 +0200 Subject: [PATCH] Move F.60 to align with TOC (#1914) --- CppCoreGuidelines.md | 66 ++++++++++++++++++++++---------------------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/CppCoreGuidelines.md b/CppCoreGuidelines.md index ffdebe8..375cb08 100644 --- a/CppCoreGuidelines.md +++ b/CppCoreGuidelines.md @@ -3230,6 +3230,39 @@ Another example, use a specific type along the lines of `variant` * Output parameters should be replaced by return values. An output parameter is one that the function writes to, invokes a non-`const` member function, or passes on as a non-`const`. +### F.60: Prefer `T*` over `T&` when "no argument" is a valid option + +##### Reason + +A pointer (`T*`) can be a `nullptr` and a reference (`T&`) cannot, there is no valid "null reference". +Sometimes having `nullptr` as an alternative to indicated "no object" is useful, but if it is not, a reference is notationally simpler and might yield better code. + +##### Example + + string zstring_to_string(zstring p) // zstring is a char*; that is a C-style string + { + if (!p) return string{}; // p might be nullptr; remember to check + return string{p}; + } + + void print(const vector& r) + { + // r refers to a vector; no check needed + } + +##### Note + +It is possible, but not valid C++ to construct a reference that is essentially a `nullptr` (e.g., `T* p = nullptr; T& r = *p;`). +That error is very uncommon. + +##### Note + +If you prefer the pointer notation (`->` and/or `*` vs. `.`), `not_null` provides the same guarantee as `T&`. + +##### Enforcement + +* Flag ??? + ### F.22: Use `T*` or `owner` to designate a single object ##### Reason @@ -3468,39 +3501,6 @@ Have a single object own the shared object (e.g. a scoped object) and destroy th (Not enforceable) This is a too complex pattern to reliably detect. -### F.60: Prefer `T*` over `T&` when "no argument" is a valid option - -##### Reason - -A pointer (`T*`) can be a `nullptr` and a reference (`T&`) cannot, there is no valid "null reference". -Sometimes having `nullptr` as an alternative to indicated "no object" is useful, but if it is not, a reference is notationally simpler and might yield better code. - -##### Example - - string zstring_to_string(zstring p) // zstring is a char*; that is a C-style string - { - if (!p) return string{}; // p might be nullptr; remember to check - return string{p}; - } - - void print(const vector& r) - { - // r refers to a vector; no check needed - } - -##### Note - -It is possible, but not valid C++ to construct a reference that is essentially a `nullptr` (e.g., `T* p = nullptr; T& r = *p;`). -That error is very uncommon. - -##### Note - -If you prefer the pointer notation (`->` and/or `*` vs. `.`), `not_null` provides the same guarantee as `T&`. - -##### Enforcement - -* Flag ??? - ### F.42: Return a `T*` to indicate a position (only) ##### Reason