Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a boost optional reference not a wrapper around a T*?

Since boost::optional<T&> is already a specialisation, why isn't it just implemented as a wrapper around T*? This would allow it to occupy less space, since there is no need for the m_initialized boolean.

like image 806
voltrevo Avatar asked Sep 17 '12 03:09

voltrevo


3 Answers

Since boost 1.61 optional is optimized in the case of references.

The release notes mention :

sizeof(optional<T&>) == sizeof(T*)

hence it's certainly implemented as a pointer in that case.

like image 171
Jean-Michaël Celerier Avatar answered Sep 18 '22 12:09

Jean-Michaël Celerier


Probably so because an uninitialized boost::optional<T*> object must be distinct from boost::optional<T*> initialized with NULL, e.g. this function can return no value, a NULL or a non-NULL pointer.

Why don't you use a plain pointer in this case with NULL indicating no value. No need to add more complexity on top of that with boost::optional<>. I mean, it is easy to make things bigger or more complex but it's hard to make them any better.

like image 33
Maxim Egorushkin Avatar answered Sep 21 '22 12:09

Maxim Egorushkin


Firstly, boost::optional<T&> is not a specialization. If you look at the code, you'll see that it does do some tag-based dispatch to customize behavior for reference types, but the boost::optional_base<T> class template itself is not specialized.

However it is still a legitimate question as to why this space optimization is not implemented. Possibly because it isn't specialized, the job is that much harder, I don't know.

The question as to why you'd prefer optional<T&> over a raw pointer is a completely separate one, so feel free to ask it separately...

like image 41
Alastair Avatar answered Sep 21 '22 12:09

Alastair