Boost Variant essentially a Union in c/c++? Boost Variant essentially a Union in c/c++? c c

Boost Variant essentially a Union in c/c++?


The primary difference is that Boost's Variant knows which type is stored in it, so you can't make mistakes or get UB from misusing a Variant in the same way you can a union. This also permits Variant to take non-POD (i.e. actually useful) types. Variant also has a few extra tricks like permitting visitors and recursive variants.

The best guide to using unions is "Don't, because it's almost impossible to put them to good use without invoking UB". This does not apply to Variant, so it's a lot safer to recommend.


Boost variant emulates a union but it does not use a union in its implementation. Instead it uses aligned storage and placement new.

It is polymorphic in the sense that if you apply a visitor object on a variant then it will pick the right overload for you. This selection must happen at runtime, but the object code for this is unrolled at compile time. So it's quite fast.