Skip to content

constexpr value on stack is lambda-captured by reference when used as conditional #38791

@clin111

Description

@clin111
Bugzilla Link 39443
Version trunk
OS Linux
CC @cpplearner,@zygoloid

Extended Description

This code is derived from the example in DR1773:

http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1773

#include <stdio.h>
struct S { int n; };
auto f() {
  S x { 1 };
  constexpr S y { 2 };
  return [&](bool b) { return (b ? y : x).n; };
}

int main(int argc, char *argv[]) {
  auto g = f();
//  int m = g(false); // undefined behavior due to access of x.n outside its lifetime
  int n = g(true);  // OK, does not access y.n
  printf("%d\n", n);
  return 0;
}

clang generates the lambda function body with references to stack memory, on both "sides" of the conditional. The program result is UB, regardless of the actual parameter value.

The example in the DR seems to imply that the front-end "should" figure out that the result is defined on the true branch of the conditional, so that g(true) always returns "2", outside the scope of f().

Without the conditional, the constant "2" is always generated as expected.
Does this example expect something that is not required by the standard?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugzillaIssues migrated from bugzillac++17clang:frontendLanguage frontend issues, e.g. anything involving "Sema"constexprAnything related to constant evaluationlambdaC++11 lambda expressions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions