简体   繁体   English

意外行为从 lambda 函数内的 std::bitset 返回一个值

[英]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::bitsetoperator[]返回一个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:您可以通过多种方式解决此问题:

  1. Explicitly specify the return type of the lambda, so the reference is converted to bool and returned by copy:显式指定 lambda 的返回类型,因此将引用转换为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];
};

Here's a demo这是一个演示

  1. Make the std::bitset in the lambda const so that it calls the const overload of operator[] , which returns a bool :使 lambda 中的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];
};

Here's a demo .这是一个演示

  1. Store the value of 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;
};

Here's a demo .这是一个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM