There’s a proposal to add optional (based on boost::optional) into C++14.
As a reference, here is Boost.Optional
Note that other languages have this, and it does come in handy (e.g. Perl has “defined”), but it has to be used carefully.
Why talk about this?
I have a use case for optional that is compelling.
I want to initialize something on first use, and then let multiple people use it, but not destroy it until after main AND after all users are done with it. This last bit is to prevent init, shutdown, init … shutdown if I have serial use. E.g. Windows Socket initialization – don’t want to call it unless someone is going to use networking code, but then I don’t want to call it multiple times if someone opens and closes sockets one after the other.
So with a shared_ptr as a global wrapped inside a Singleton pattern, I get most of that – I get to have ref-counting, and then the fact that it’s a global means I have a ref count maintained until after main. BUT – I get initialized at startup, which I don’t want. If my singleton contains a pointer to the resource, then I avoid init-at-startup, but now I either don’t have a shareable refcount, or I need some code at shutdown – which I can’t schedule properly.
But if I wrap my global as an optional, then I get both – I get C-level initialization, because an optional is so very close to a POD type that there’s no work needed for the constructor other than zero-initialization (which is guaranteed for global objects), and I have a destructor on the contained value once I initialize it.
I still dislike most of the use cases I’ve seen optional used for, but this one is something I’m going to use.
I was reading the C++14 proposal for optional, and I saw mention of value_or.
will pass optvar.value to process, if optvar is engaged (i.e. has a contained value), or it will pass 0. This would make a lot of the code I’ve seen more compact and readable.
Things are slightly different between C++03 and C++11. And I have to do some experiments to see if optional fits into C++03 zero-initialization rules or if it requires C++11 constant initialization rules. Since optional is really just a boolean and a raw array, it should be zero-initialized.