C++ Logo

std-proposals

Advanced search

[std-proposals] const reference captures in lambdas

From: JJ Marr <jjmarr_at_[hidden]>
Date: Sat, 21 Jun 2025 21:06:45 -0400
For function parameters that are slow to copy, we have const references.
For lambda captures that are slow to copy, we do not have an easy
equivalent.

The easiest way to do this is:

```cpp
#import <functional>
#import <utility>
    int var;
    [newVar = std::cref(var)](){
        // body
    };

    [&newVar = std::as_const(var)](){
        // body
    };
```

This requires importing the functional (for std::cref) or utility (for
std::as_const) headers. It also requires the creation of a new identifier,
possibly with a different name to avoid variable shadowing warnings.

We should be able to `const`-qualify a lambda capture. For captures
by-value on a non-mutable lambda, this would have no effect because
value-captures cannot be modified. For reference captures or a mutable
lambda, this would have the same behaviour as `const` on any other
identifier (cannot modify/call non-const members/etc). A possible syntax
would be:

```cpp
    [const &var](){
        // body
    };
```

Open questions:
* Should we allow for other/arbitrary qualifiers? i.e. volatile?
* Can we apply qualifiers to a default capture? e.g.:

```cpp
    [const &](){
        // body
    };
```

Appreciate feedback on whether this is a good enough idea to turn into a
proposal.
--
JJ Marr

Received on 2025-06-22 01:06:57