Why do the C++ Core Guidelines not recommend to use std::optional over pointers when approriate?

559 Views Asked by At

In the C++ Core Guidelines std::optional is only referred once:

If you need the notion of an optional value, use a pointer, std::optional, or a special value used to denote “no value.”

Other than that, it is not mentioned in the guidelines, so in particular there is no recommendation to use it instead of a pointer, when expressing the intent of an optional value.

Are there any disadvantages of the usage of std::optional in comparison to a pointer that might be null in a non-polymorphic context?

So std::optional is only referred as a side note and as the second option to a pointer. To me it seems like that std::optional is much more expressive. When using a pointer, you can never be really sure if the option of a nullptr is intended.

1

There are 1 best solutions below

2
On BEST ANSWER

That guideline is not listing things in order of "pick this first". It is listing options that are appropriate in different situations, and leaves it up to you which is most appropriate for your situation.

In particular, choosing between (const)T* and std::optional<T> is the same as choosing between (const)T& and T. Adapting the examples of the enclosing rule, you'd have

// optional<int> is cheap to copy, pass by value
optional<int> multiply(int, optional<int>); 

// suffix is optional and input-only but not as cheap as an int, pass by const*
string& concatenate(string&, const string* suffix); 

Aside: If you follow the other guidelines, then you can be sure that a pointer indicates a situation where "no value" is an expected case.