gpt4 book ai didi

c++ - 为什么我使用 std::variant 获得 std::bad_variant_access?

转载 作者:行者123 更新时间:2023-12-01 15:08:03 30 4
gpt4 key购买 nike

考虑:

#include <variant>
#include <iostream>

int main()
{
double foo = 666.666;
std::variant<double, uint64_t> v = foo;
std::cout << std::get<uint64_t>(v) << std::endl;
return 0;
}

这导致:

terminate called after throwing an instance of 'std::bad_variant_access'
what(): Unexpected index
Aborted (core dumped)

为什么?

我了解到 std::variant 将替代 union。但是,如果这种基本的东西失败了,它有什么用呢?

最佳答案

I have understood that std::variant would be a replacement for union.

是的。有点儿。但是您的误解似乎与 C++ 中的 union 有关。来自 cppreference :

It's undefined behavior to read from the member of the union that wasn't most recently written. Many compilers implement, as a non-standard language extension, the ability to read inactive members of a union.

请注意,这与 C 不同,这是导致 C++ 也允许访问非事件成员的常见误解的根本原因之一。

Why?

因为 std::variant模仿 union 但增加了一些安全和 std::get 是……

Index-based value accessor: If v.index() == I, returns a reference to the value stored in v. Otherwise, throws std::bad_variant_access. The call is ill-formed if I is not a valid index in the variant.

.

But if this kind of basic stuff fails what is it good for?

C++ 中的 union 从来就不是这样使用的。当您想将两个或多个值压缩到同一内存中(但任何时候只使用其中一个)时, union 更节省内存。我从来没有遇到过他们的真实用例。 std::variant然而,它是对 C++ 类型的一个很好的补充。更大的图景是很久以来就有所谓的产品类型,比如std::pair<T1,T2>。 ,从某种意义上说,它们可以表示的值集是 T1 x T2 .与 std::variant (和 std::any )现在 C++ 也有适当的(= 具有一定程度的类型安全性,你从未从 union 中获得)和类型,即值集 a std::variant<T1,T2>可以表示是T1 + T2 (抱歉使用草率的符号,希望它是清楚的)。

关于c++ - 为什么我使用 std::variant 获得 std::bad_variant_access?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61230917/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com