Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ idiomatic way for nullable reference

I am writing a function which should accept const std::string &, but also a special nullptr value. Currently, I'm using const std::string *. However, I feel that there should be a more C++-ish way to perform this task.

My strongest counterpoint is passing by value (the string won't be really long but 64kB is not something I want copied around). That also implies that I want no object like optional<T> which would have a value field of type T. Also, I don't want to use any external libraries. My project is not using Boost or GSL, just plain C++ (C++17 to be exact).

Is there a standard library class (miracles occur in namespace std) or a widely accepted idiom for such situation?

like image 309
Top Sekret Avatar asked Dec 17 '22 16:12

Top Sekret


1 Answers

If std::optional supported references, it'd be the fancy "modern" way to do this.

But:

  • it doesn't, and
  • sometimes being fancy and "modern" is not all that it is cracked up to be.

The age-old, tried-and-tested and clear-to-read solution is to take a pointer. This approach does absolutely everything that you need it to do.

Just do that, then move on to spend your precious time on more important matters!

like image 158
Lightness Races in Orbit Avatar answered Jan 03 '23 05:01

Lightness Races in Orbit