[Bug c++/58181] A bug in lambda expression

daniel.kruegler at googlemail dot com gcc-bugzilla@gcc.gnu.org
Sat Aug 17 16:19:00 GMT 2013


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=58181

--- Comment #3 from Daniel Krügler <daniel.kruegler at googlemail dot com> ---
My understanding is that the presented program has undefined behaviour and that
its assertion may fail or may not. The reason being that the outer lambda
expression has return type std::tuple<LI&&> (where LI stands for an invented
name for the inner lambda closure type), but during runtime the reference in
the tuple refers to a temporary of LI created within the operator() body of the
outer lambda closure type LO that has been gone out of existence after the
function call has been finished.

The following code represents a translation of the single expression to
equivalent C++ code w/o use of any lambda expressions:

#include <tuple>
#include <cassert>

struct LI
{
  LI(int x) : x(x) {}
  int operator()() const { return x; }
  int x;
};

struct LO
{
  std::tuple<LI&&> operator()() const
  {
    int x = 0;
    return std::forward_as_tuple(LI(x));
  }
};

int main()
{
  assert(std::get<0>(LO{}())() == 0);
}

This rewrite makes the invalid code more obvious.


More information about the Gcc-bugs mailing list