In the Names exercise, you were to convert from using std::string
and a flag:
To using std::optional
:
If you did the following, we have all sorts of potential memory issues because std::string_view
does not have any storage of its own, and you will likely have a memory issue at some point in development.
I am unsure why anybody would do this as the problem never said to change the string type, but only to use std::optional
.
For the return type of the get() methods, if the return type of a get() method is the same as the type of the field (or a const reference of the field type), then we can return the field:
So for the Names exercise, if we return with a std::string
, we have issues:
First, dereferencing of *firstName
can cause a crash if it is not defined. Remember, we have to check it first.
Second, what do we do when firstName
has no value? Return an empty string? Wouldn't a client of class Name want to know if it exists?
The answer is to return a std::optional<std::string>
:
In the first implementation, the return of a *firstName
will compile and work in many cases, but it can potentially cause a crash if firstName
does not have a value. The second implementation works but has a lot of unnecessary logic. The third implementation is an instance of the get() method return type.