string_view
operator+
vs. StrCat()
absl::Status
std::bind
absl::optional
and std::unique_ptr
absl::StrFormat()
make_unique
and private
Constructors.bool
explicit
= delete
)switch
Statements Responsibly= delete
AbslHashValue
and Youcontains()
std::optional
parametersif
and switch
statements with initializersinline
Variablesstd::unique_ptr
Must Be MovedAbslStringify()
vector.at()
Originally posted as TotW #186 on November 5, 2020
By James Dennett and Jason Rennie
Updated 2020-11-05
Quicklink: abseil.io/tips/186
“Everything should be made as simple as possible, but no simpler.” ~ Roger Sessions’s interpretation of Einstein
When adding a new function, default to making it a non-member function local to
the .cc
file where it is called. While there are valid reasons to make another
choice, consider writing it in an unnamed namespace (also known as an “anonymous
namespace”).
Writing a non-member in an unnamed namespace has benefits both by making
functions internal to a .cc
file (moving them out of header files) as well as
by making them non-members (moving them out of classes).
Benefits over functions declared in a header file include:
Benefits over private methods include:
Most of these benefits remain even if there is no relevant header file, such as
for a *_test.cc
or a *_main.cc
file.
Sometimes a non-member local function does not make sense. For example:
static
Non-Member FunctionsMarking a non-member function as static
has essentially the same effect as
placing it inside an unnamed namespace in terms of isolating it from code in
other translation units. While unnamed namespaces do this in a uniform manner
that covers types as well as functions and objects, some people like to see
static
written explicitly in the declaration of a function to show that it is
local to a translation unit without having to check for an enclosing unnamed
namespace. While this tip recommends using an unnamed namespace, using static
can be a reasonable choice.
Parts of the style guide point us in this direction, but they don’t go as far. For example:
static
), but doesn’t talk about private methods.this
); this
is essentially an uber-input/output parameter.File-local functions simplify dependencies and improve locality. Non-member
functions increase encapsulation, simplify class definitions, and make
dependencies more explicit. When writing a function, consider making it a
file-local non-member function, such as by putting it in an unnamed namespace of
a .cc
file.