简体   繁体   English

代码块和Lambdas C ++ 11

[英]Code blocks & lambdas c++11

please, can any one explain me, how conditionalVariable will be stored in this case, to be used while check_calls_on_current_floor calling outside the condition block? 请问谁能解释我,在这种情况下将如何存储conditionalVariable,以便在condition_block外部调用check_calls_on_current_floor时使用?

std::function<bool()> check_calls_on_current_floor;
if (/*Some condition*/)
{
    const int conditionalVariable = /*some value*/;

    check_calls_on_current_floor = [&](){ 
        return conditionalVariable == 10; };
}
check_calls_on_current_floor();

It seems like in this case we, can access this variable outside the condition block, in case we got lambda from there. 似乎在这种情况下,我们可以在条件块之外访问此变量,以防我们从那里获取lambda。

It's a dangling reference. 这是一个悬而未决的参考。 It's undefined behavior to make that call after the if block. if块之后进行调用是未定义的行为。 It's very similar to returning a reference to a local variable from a function. 这与从函数返回对局部变量的引用非常相似。 It's even more similar to this: 与此类似:

struct ref_holder
{
    ref_holder(const int & r) :ref(r) {}
    const int & ref;
};

int main()
{
    std::unique_ptr<ref_holder> ptr;
    if (true)
    {
        const int conditionalVariable = 10;

        ptr.reset(new ref_holder(conditionalVariable));
    }
    ptr->ref == 10; // undefined behavior
}

It's somewhat analogous to this: 这有点类似于:

int x = 0;
int* z = &x;
if (condition)
{
    int y = 1;
    z = &y;
}

If the condition holds, then z will be pointing to y which has gone out of scope. 如果条件成立,则z将指向超出范围的y

This conditionalVariable out of it's scope but in extent. 此conditionalVariable超出其范围,但在一定程度上。

I think this will help you. 我认为这会对您有所帮助。 http://en.wikipedia.org/wiki/Variable_(computer_science)#Scope_and_extent http://en.wikipedia.org/wiki/Variable_(computer_science)#Scope_and_extent

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

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