Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm wondering what the differences are between a Boost Variant and a union data-type in c/c++. I know that a union data-type takes up the same memory location and the largest data type in the region of memory occupies the total amount of memory used e.g.

union space {
   char CHAR;
   float FLOAT;
   int INTEGER;
}S;

should occupy 4 bytes of memory since int and float are the largest and equal size. Are there similarities and differences in other ways between Boost Variant and union data types? I also know that a Boost Variant can take any data type and it allows data type "polymorphism" (correct me if I'm misusing a OOP topic word). Is a union data type therefore a type of polymorphism also?

like image 709
pandoragami Avatar asked Jul 27 '13 19:07

pandoragami


2 Answers

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.

like image 84
Puppy Avatar answered Nov 12 '22 08:11

Puppy


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.

like image 12
StackedCrooked Avatar answered Nov 12 '22 09:11

StackedCrooked