In C++, if you want to pass a pointer as an out or in/out parameter, you pass it by reference:
int x;
void f(int *&p) { p = &x; }
But, a reference can't ("legally") be nullptr
, so, if the pointer is optional, you need a pointer to a pointer:
void g(int **p) { if (p) *p = &x; }
Sure, since C++17 you have std::optional
, but, the "double pointer" has been idiomatic C/C++ code for many decades, so should be OK. Also, the usage is not so nice, you either:
void h(std::optional &p) { if (p) *p = &x) }
which is kind of ugly at the call site, unless you already have a std::optional
, or:
void u(std::optional> p) { if (p) p->get() = &x; }
which is not so nice in itself.
Also, some might argue that g
is nicer to read at the call site:
f(p);
g(&p); // `&` indicates that `p` might change, to some folks