Posts

Showing posts from July, 2020

Member Variable Initialization via With[...] Methods

There are a number of ways to initialize member variables in C++. One of the "recommended" methods is via a constructor, and arguments to it. While this is functional, I've personally been gravitating away from this paradigm in my own code of late, especially when there are multiple parameters involved, or multiple constructor overloads for different initialization scenarios. As the use-cases get more complex, it becomes harder to reason about the parameters passed, and more prone to maintenance-related errors. The alternative method I'm gravitating toward is this: class CFoo {      int nSomeValue = 0;      inline auto& WithSomeValue( int nValue )      {           nSomeValue = nValue;           return *this;      } }; Why is this "better" (for some subjective measurement of better)? Members are named and self-explanatory, rather than positional You do not ha...

std::optional<> is Useful

Consider this: How many times have you written code where a specific value for a type represents an implicit "empty" value? For example, a string value where an empty string was implicitly "no value"? A number where zero was the "default", "no value" case? How many times has that bitten you later, where you needed to add secondary variables to indicate if the first value was valid or not? Alternatively, how many data structures have values which may or may not be populated by a caller, and the callee needs to rely on additional or implicit information to discern if the values are valid or not? Enter std::optional<> (or previously boost::optional<>). This type can be used to express the "null" state for any type, without using secondary variables, implicit value meanings, or other mechanisms (eg: using pointers which might be null). Usage is easy: std::optional<std::string> osValue; osValue.has_value(); // yields false ...