I encountered the following situation while refactoring old code:
// pointers to const are discouraged in our code base
void Do(Foo* exists, Foo* maybe_null) {
// does not change *exists or *maybe_null
}
int main() {
// ...
Do(&foos[i], test_both ? &bars[i] : nullptr);
// ...
}
So, Do
is called with two Foo
objects of which one definitely exists while the second might not, depending on some outside test. Issues I have with this current code that I am trying to solve:
-
The first parameter will never be null so its pointer properties are never used.
-
I generally dislike the use of null as an empty value.
So far I came up with three possible solutions, none of which I am completely satisfied with:
-
Do(const Foo&, Foo*)
: The second argument has the same issue as before and now the call syntax is not uniform anymore (foos[i]
and&bars[i]
), which might confuse readers. -
Do(const Foo&, const optional<<T>Foo>&)
: The secondFoo
object has to be copied to construct the optional. -
Do(const Foo&, optional<<T>const Foo&>)
: Does not actually work since optional of a reference type is disallowed.
So, are there any better/cleaner solutions I could use in this situation?
(I am using C++11 with some std additions like optional)
Aucun commentaire:
Enregistrer un commentaire