[英]Unexpected behavior return a value from a std::bitset inside a lambda function
I am trying to use the value from a std::bitset inside of a lambda function but I am experiencing unexpected behavior:我试图在 lambda 函数内使用 std::bitset 中的值,但我遇到了意外行为:
int main()
{
auto lambda = [](unsigned int param)
{
std::bitset<10> bits(param);
std::cout << "inside lambda bits[8] = " << bits[8] << std::endl;
return bits[8];
};
// 0x11c is 1_0001_1100 in binary
auto result = lambda(0x11c);
std::cout << "result = " << result << std::endl;
}
I would expect the value of result to be one since result is of type bool which can be copied from the local stack but instead the output is the following:我希望 result 的值为 1,因为 result 是 bool 类型,可以从本地堆栈复制,但输出如下:
inside lambda bits[8] = 1
result = 0
What am I overlooking here?我在这里俯瞰什么?
The operator[]
for std::bitset
returns a std::bitset::reference
when called on a non-const std::bitset
.当在非常量
std::bitset
上调用时, std::bitset
的operator[]
返回一个std::bitset::reference
。 This means the lambda (which deduces the return type), returns a reference to a local variable.这意味着 lambda(推导出返回类型)返回对局部变量的引用。 This obviously dangles, and invokes undefined behavior when used at the call site.
这显然是悬而未决的,并且在调用站点使用时会调用未定义的行为。
You can fix this in several ways:您可以通过多种方式解决此问题:
bool
and returned by copy:bool
并通过 copy 返回:auto lambda = [](unsigned int param) -> bool
// ^^^^
{
std::bitset<10> bits(param);
std::cout << "inside lambda bits[8] = " << bits[8] << std::endl;
return bits[8];
};
std::bitset
in the lambda const
so that it calls the const
overload of operator[]
, which returns a bool
:std::bitset
成为const
以便它调用operator[]
的const
重载,它返回一个bool
:auto lambda = [](unsigned int param)
{
std::bitset<10> const bits(param);
// ^^^^^
std::cout << "inside lambda bits[8] = " << bits[8] << std::endl;
return bits[8];
};
bits[8]
as a bool
, and return that:bits[8]
的值存储为bool
,并返回:auto lambda = [](unsigned int param)
{
std::bitset<10> bits(param);
std::cout << "inside lambda bits[8] = " << bits[8] << std::endl;
bool b = bits[8];
// ^^^^^^
return b;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.