Where to use std::variant over union?

久未见 提交于 2019-12-09 07:30:34

问题


Please explain what is the difference between union and std::variant and why std::variant was introduced into the standard? In what situations should we use std::variant over the old-school union?


回答1:


Generally speaking, you should prefer variant unless one of the following comes up:

  1. You're cheating. You're doing type-punning or other things that are UB but you're hoping your compiler won't break your code.

  2. You're doing some of the pseudo-punnery that C++ unions are allowed to do: conversion between layout-compatible types or between common initial sequences.

  3. You explicitly need trivial copyability and/or layout compatibility. variant<Ts> are not required to have any particular layout or trivial copyability. unions of standard layout types are standard layout, and unions of trivially copyable types are trivially copyable.

    Note that there is a proposal to make variant trivially copyable if its component types are trivially copyable. It's proposed as a defect report against C++17, so this behavior would effectively be backported into C++17.

  4. You need low-level support for in-place switching of objects. Using a memory buffer for such things doesn't provide the trivial copying guarantees that you could get out of a union.

The basic difference between the two is that variant knows which type it stores, while union expects you to keep track of that externally. So if you try to access the wrong item in a variant, you get an exception or nullptr. By contrast, doing so with a union is merely undefined behavior.

union is a lower-level tool, and thus should only be used when you absolutely need that lower-level.

variant also has machinery for doing visitation, which means you get to avoid having a bunch of if statements where you ask "if it is type X, do this. If it is type Y, do that, etc".



来源:https://stackoverflow.com/questions/42082328/where-to-use-stdvariant-over-union

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