vikram2784
vikram2784

Reputation: 822

Behaviour of a closure that captures a local variable of function that it was returned from, in C++

I am bit a confused why the following functions normal_get() and closure_get() behave differently. Sure, one returns a closure and the other a reference to a local variable. But essentially the former return value (closure) when invoked, does the same thing i.e returns a reference to a local variable of the function that it was returned from.

I am no c++ expert and I know one cannot a return a reference to a local variable within a function. But I would like to confirm whether it is an undefined or expected behavior for the closure scenario and there is no compiler magic there? (asking since I have recently started playing around with closures in C++)

I am using g++ 9.3.0

g++ -std=c++2a test.cpp


#include <iostream>
#include <functional>

using namespace std;


auto closure_get() {
        int val = 10;

        auto f = [&]() {       // capturing by reference
                return &val;
        };

        return f;
}

auto normal_get() {
        int val = 10;

        return &val;
}


int main () {
        auto func = closure_get();
        auto val = normal_get();

        std::cout<<*func()<<std::endl;  // This always prints `10`. Should this be considered as undefined behavior though?
        std::cout<<*val<<std::endl;     // This always segfaults as expected. It's still undefined behavior even if it prints some value.
}

Upvotes: 1

Views: 201

Answers (1)

foragerDev
foragerDev

Reputation: 1409

In both cases it is undefined behavior as any non-static local variable cannot be returned as reference or pointer as it is destroyed after the end of the scope of that function. So that reference or pointer will be invalid.

Upvotes: 3

Related Questions