I have the following code:
MyType x = do_something_dangerous();
// ...
if (some_condition) {
// ...
bar(x);
}
else {
// ...
}
// ...
if (another_condition_which_may_depend_on_previous_if_else} {
// ...
baz(x);
}
The idea is that in some cases, which are perhaps difficult/inconvenient to determine in advance, I need to use x
. But in the cases I don't need to use it, trying to initialize it may be bad (say, could crash my process).
Now, it seems like what I need to be using is an initialize-on-demand holder (the link focuses on Java, so here's a sketch): Some kind of Wrapper<MyType>
or Wrapper<MyType, do_something_dangerous>
with a get()
method, such that the first get()
calls do_something_dangerous()
and later get()
s just pass the value the first call obtained.
- Is this indeed an appropriate approach here?
- Is there some standard(ish) implementation of this idiom, or a variant of it?
Notes:
- I could use
boost::optional
, but that would be a bit cumbersome and also twist the intended use: "It is recommended to useoptional<T>
in situations where there is exactly one, clear (to all parties) reason for having no value of typeT
, and where the lack of value is as natural as having any regular value ofT
."