Cppcoreguidelines: F.52 explanation should mention on how to achieve const reference capture

Created on 29 May 2018  路  5Comments  路  Source: isocpp/CppCoreGuidelines

While efficient it might not be obvious how to capture a mutable (large) variable by const reference.

One option is to use std::cref():

std::vector<double> var(1'000'000);
[cr=std::cref(var)](){ /* use cr safely here */}

Most helpful comment

may be the gsl should provide as_const(x) then?

All 5 comments

Or [&cr = std::as_const(var)]{ }

as always jwakely is more precise and suggests the better solution...

Although my suggestion is only valid for C++17 and later. The C++14 version is ugly:

[&cr = const_cast<const T&>(var)] { }

or if you don't know T it's even worse:

[&cr = const_cast<remove_reference_t<decltype(var)> const&>(var)] { }

So for C++14 std::cref seems appropriate (as long as it doesn't matter that cr is not const T&, only convertible to it).

may be the gsl should provide as_const(x) then?

Editors call: We decided to not get into the detail of capturing a const reference at this time, but plan to look at it again next time we revise this item.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

TomMettam picture TomMettam  路  3Comments

vingeldal picture vingeldal  路  4Comments

larsch picture larsch  路  4Comments

franzhollerer picture franzhollerer  路  5Comments

franzhollerer picture franzhollerer  路  6Comments