17

Given the following sample code:

int main()
{
    int i;
    auto f = [=]()mutable->int*
    {
            return &i;
    };

    return 0;
}
  1. g++ v.4.8.1 warns that "address of local variable ‘i’ returned".
  2. Clang v.3.2 (MacOS's Clang) warns that "address of stack memory associated with local variable 'i' returned".
  3. Neither VS2012 nor VS2013 RC warn of anything.

My understanding of lambdas is that the compiler will generate a functor class. That functor class will have members for all copied variables (i in the example). I believe that in the context of my code, as long as f exists, it is safe to return the address of one of its members. It seems to me that all compilers got it wrong. I think a warning about using the address of f's member i after f goes out of scope is valid, but the warnings about the "local variable 'i'" are incorrect/misleading. Am I right?

8
  • You can make i static. Sep 22, 2013 at 22:56
  • The functor class will have a reference to "i", but "i" is itself still just a local variable on the stack. Once main() returns, i no longer exists.
    – joeking
    Sep 22, 2013 at 22:57
  • 1
    @joeking he is asking about the error, for example you don't get the same error with this code even though it's exactly the same: struct S { int* operator()() { return &i; } int i; } f;
    – Kal
    Sep 22, 2013 at 22:58
  • 2
    @joeking Can you elaborate? He's capturing i by value ([=]), so why would it have a reference? Also, nobody is contesting that it's all out of scope after main() returns.
    – us2012
    Sep 22, 2013 at 22:58
  • also i think this code has undefined behavior since you copy i without initializing it :(
    – Kal
    Sep 22, 2013 at 22:59

2 Answers 2

7

Yes, you're right. The & operator is applying to the member, not the local object.

Demonstration is straightforward: just modify your example to output the addresses.

#include <iostream>

int main() {
    int i;
    std::cout << & i << '\n';

    std::cout << [=]() mutable -> int * {
        return & i;
    } () << '\n';
}

http://ideone.com/OqsDyg

Incidentally, this compiles with no warnings under -Wall in GCC 4.9.

2
  • I'm very much inclined to believe you, as you have numerous great answers on C++ questions, but honestly some explanation or sources would be nice. I think we've all tried that example or something similar, but the big question is, how do we know we can rely on this behaviour?
    – us2012
    Sep 22, 2013 at 23:46
  • 1
    @us2012 Don't know what I can add… the OP's belief about how it works is correct. The standardese which specifies lambdas is rather involved; I don't know how helpful it would be. Every use of a name from the surrounding local context is actually naming a functor member, and that member is either a reference or a copy. Some compilers apparently erroneously assume(d) it's a reference, but I suspect the error only goes as far as the message, because otherwise mutable would be broken. Sep 22, 2013 at 23:49
4

Some terminology:

  • The = or & inside [&](){ /*..*/ } is called a capture-default.
  • odr-use of a variable roughly means that the variable does not appear in a discarded-value-expression (such as (void)some_variable or int x = some_variable, 5;) and it doesn't occur in a constant expression.
  • compound-statement is the "function block" { statements }
  • the name of a variable is an id-expression

[expr.prim.lambda]/3

The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type — called the closure type — whose properties are described below.

/11

If a lambda-expression has an associated capture-default and its compound-statement odr-uses (3.2) this or a variable with automatic storage duration and the odr-used entity is not explicitly captured, then the odr-used entity is said to be implicitly captured;

Therefore, i is implicitly captured.

/14

An entity is captured by copy if it is implicitly captured and the capture-default is = or if it is explicitly captured with a capture that does not include an &. For each entity captured by copy, an unnamed non-static data member is declared in the closure type.

There is a non-static data member (of type int) in the closure type.

/17

Every id-expression that is an odr-use (3.2) of an entity captured by copy is transformed into an access to the corresponding unnamed data member of the closure type.

We don't even need to interpret this, as this paragraph provides us with an example very similar to the OP's:

void f(const int*);
void g() {
    const int N = 10;
    [=] {
        int arr[N]; // OK: not an odr-use, refers to automatic variable
        f(&N);      // OK: causes N to be captured; &N points to the
                    // corresponding member of the closure type
    };
}

If we apply this to the OP's example, we see that &i refers to the internal non-static data member of the closure type. Whether or not the diagnostic message is appropriate is not specified in the Standard ;)

1
  • [basic.scope.block]/1 says that "A variable declared at block scope is a local variable." Therefore, the OP's lambda does not return the address of a local variable.
    – dyp
    Sep 23, 2013 at 0:18

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.