lllShamanlll
lllShamanlll

Reputation: 184

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?

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.

Upvotes: 1

Views: 169

Answers (2)

Timothy Shields
Timothy Shields

Reputation: 79461

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.

Upvotes: 1

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

It's a dangling reference. It's undefined behavior to make that call after the if block. 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
}

Upvotes: 3

Related Questions