Bug 66735 - [C++14] lambda init-capture fails for const references
Summary: [C++14] lambda init-capture fails for const references
Status: RESOLVED FIXED
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 5.1.0
: P3 normal
Target Milestone: 7.0
Assignee: Nathan Sidwell
URL:
Keywords: c++-lambda, rejects-valid
: 70385 (view as bug list)
Depends on:
Blocks: lambdas
  Show dependency treegraph
 
Reported: 2015-07-02 09:19 UTC by Anton Savin
Modified: 2022-03-11 00:32 UTC (History)
5 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2015-12-05 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Anton Savin 2015-07-02 09:19:06 UTC
This code fails to compile:

int main() {
    int x = 0;
    auto l = [&rx = static_cast<const int&>(x)]() {};
}


The error message is:

test.cpp:3:14: error: binding 'const int' to reference of type 'int&' discards qualifiers
     auto l = [&rx = static_cast<const int&>(x)]() {


But according to [expr.prim.lambda]/11 rx should be captured as auto &rx = static_cast<const int&>(x), that is as const int&.

Tested on MacPorts g++-mp-5:

$ g++-mp-5 -v
Using built-in specs.
COLLECT_GCC=g++-mp-5
...
gcc version 5.1.0 (MacPorts gcc5 5.1.0_1)
Comment 1 aaron.mcdaid 2015-08-10 12:49:39 UTC
I'm also seeing the same problem, and another very similar issue:

    int main() {
        const int x = 0;
        auto l = [&rx = x]() {};
    }

This is rejected by g++ (4.9.3 and 5.2.0) but accepted  by clang. Also discussed on StackOverflow: http://stackoverflow.com/q/31919260/146041
Comment 2 Markus Trippelsdorf 2015-12-05 12:51:44 UTC
Confirmed.
Comment 3 Zhihao Yuan 2016-01-07 04:20:22 UTC
As the standardization of `std::as_const`, this bug becomes a blocker.
Comment 4 Nathan Sidwell 2016-12-29 15:40:53 UTC
int const x = 5;

void Foo ()
{
  auto l = [&rx = x]() {};
}
Comment 5 Nathan Sidwell 2016-12-29 15:41:59 UTC
*** Bug 70385 has been marked as a duplicate of this bug. ***
Comment 6 Nathan Sidwell 2017-01-04 15:24:21 UTC
Author: nathan
Date: Wed Jan  4 15:23:40 2017
New Revision: 244056

URL: https://gcc.gnu.org/viewcvs?rev=244056&root=gcc&view=rev
Log:
	cp/
	PR c++/66735
	* cp-tree.h (DECLTYPE_FOR_REF_CAPTURE): New.
	(lambda_capture_field_type): Update prototype.
	* lambda.c (lambda_capture_field_type): Add is_reference parm.
	Add referenceness here.
	(add_capture): Adjust lambda_capture_field_type call, refactor
	error checking.
	* pt.c (tsubst): Adjust lambda_capture_field_type call.

	testsuite/
	PR c++/66735
	* g++.dg/cpp1y/pr66735.C: New.

Added:
    trunk/gcc/testsuite/g++.dg/cpp1y/pr66735.C
Modified:
    trunk/gcc/cp/ChangeLog
    trunk/gcc/cp/cp-tree.h
    trunk/gcc/cp/lambda.c
    trunk/gcc/cp/pt.c
    trunk/gcc/testsuite/ChangeLog
Comment 7 Nathan Sidwell 2017-01-04 15:25:03 UTC
Fixed trunk r244056.