Bug 70385 - Lambda capture by reference of const reference fails
Summary: Lambda capture by reference of const reference fails
Status: RESOLVED DUPLICATE of bug 66735
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 6.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: c++-lambda, rejects-valid
Depends on:
Blocks: lambdas
  Show dependency treegraph
 
Reported: 2016-03-23 23:44 UTC by Nik Bougalis
Modified: 2022-03-11 00:32 UTC (History)
4 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail: 5.3.0, 6.1.0, 7.0
Last reconfirmed: 2016-07-01 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Nik Bougalis 2016-03-23 23:44:20 UTC
Consider the following minimal MCVE:

    const int& test()
    {
        int const static i = 0;
        return i;
    }

    int
    main()
    {
        auto square = [&j = test()]()
        {
        };

        return 0;
    }

The expectation here is that `pays` will be a `const int&`. Clang successfully compiles this code (along with a warning about j being unused) but gcc fails to compile with an interesting error:

error: binding 'const int' to reference of type 'int&' discards qualifiers
                 &j = test()
                     ~~~~~^~

This is clearly wrong. I believe that the correct behavior would be for `j` to be a `const int&`.


We can simplify the example a bit more. The following code successfully compiles and appears to do the "right" thing on both clang and gcc:

int
main()
{
    int const i = 0;
       
    auto test = [&i]()
    {
    };
    
    test();
    return 0;
}

The following code compiles and does the "right" thing in clang, but not in gcc, where compilation fails:

int
main()
{
    int const i = 0;
       
    auto test = [&j = i]()
    {
    };
    
    test();
    return 0;
}
Comment 1 Viktor Ostashevskyi 2016-06-29 15:31:47 UTC
I can confirm this with:

gcc version 5.3.1 20160329 (GCC)

and 

gcc version 6.0.0 20160403 (experimental) (GCC).

It also fails with x86 gcc 6.1 (g++ (DRW-internal-build) 6.1.0) on gcc.godbolt.org
Comment 2 Martin Sebor 2016-07-01 23:07:33 UTC
Confirmed with today's top of trunk (7.0).  The code never seems to have been accepted.

$ cat xxx.c && /build/gcc-trunk-svn/gcc/xgcc -B /build/gcc-trunk-svn/gcc -S -Wall -Wextra -Wpedantic -xc++ xxx.c
int const i = 0;
auto test = [&j = i]() { };
xxx.c:2:13: error: binding ‘const int’ to reference of type ‘int&’ discards qualifiers
 auto test = [&j = i]() { };
             ^
Comment 3 Nathan Sidwell 2016-12-29 15:41:59 UTC
Same as 66735, to which I have attached a simpler testcase

*** This bug has been marked as a duplicate of bug 66735 ***