What is boost::variant memory and performance cost?

核能气质少年 提交于 2019-11-30 11:47:32
o11c

You're almost right.

The size of boost::variant is is the max size of any element, rounded up as needed for the largest alignment, plus the size of some integer, and again rounded up.

Think about a variant of these types, assuming the tag is uint32_t:

struct foo { uint32_t value[3]; }; // size 12, align 4
struct bar { uint64_t v2; }; // size 8, align 8

An untagged union must have size 16, align 8; adding the 4-byte tag must go up to size 24 to keep align 8.

Or consider a variant of:

struct foo { uint8_t value[5]; }; // size 5, align 1
struct bar { uint16_t v2; }; // size 2, align 2

An untagged union of these must have size 6, align 2; adding the 4-byte tag forces you to size 12, align 4.

For calling, I expect it uses an array-of-functions lookup (that's how I implemented my own variant, which was necessary since boost's didn't support move constructors), since if chains don't perform well and switches are impossible.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!