1

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.

1

2 Answers 2

3

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.