Lambda capture as const reference?

C++C++11LambdaC++14

C++ Problem Overview


Is it possible to capture by const reference in a lambda expression?

I want the assignment marked below to fail, for example:

#include <algorithm>
#include <string>

using namespace std;

int main()
{
    string strings[] = 
    {
        "hello",
        "world"
    };
    static const size_t num_strings = sizeof(strings)/sizeof(strings[0]);

    string best_string = "foo";

    for_each( &strings[0], &strings[num_strings], [&best_string](const string& s)
      {
        best_string = s; // this should fail
      }
    );
return 0;
}

Update: As this is an old question, it might be good to update it if there are facilities in C++14 to help with this. Do the extensions in C++14 allow us to capture a non-const object by const reference? (August 2015)

C++ Solutions


Solution 1 - C++

In [tag:c++14] using static_cast / const_cast:

[&best_string = static_cast<const std::string&>(best_string)](const string& s)
{
    best_string = s; // fails
};

DEMO


In [tag:c++17] using std::as_const:

[&best_string = std::as_const(best_string)](const string& s)
{
    best_string = s; // fails
};

DEMO 2

Solution 2 - C++

const isn't in the grammar for captures as of n3092:

capture:
  identifier
  & identifier
  this

The text only mention capture-by-copy and capture-by-reference and doesn't mention any sort of const-ness.

Feels like an oversight to me, but I haven't followed the standardization process very closely.

Solution 3 - C++

I think the capture part should not specify const, as the capture means, it only need a way to access the outer scope variable.

The specifier is better specified in the outer scope.

const string better_string = "XXX";
[&better_string](string s) {
    better_string = s;    // error: read-only area.
}

lambda function is const(can't change value in its scope), so when you capture variable by value, the variable can not be changed, but the reference is not in the lambda scope.

Solution 4 - C++

I guess if you're not using the variable as a parameter of the functor, then you should use the access level of the current function. If you think you shouldn't, then separate your lambda from this function, it's not part of it.

Anyway, you can easily achieve the same thing that you want by using another const reference instead :

#include <cstdlib>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    string strings[] = 
    {
        "hello",
        "world"
    };
    static const size_t num_strings = sizeof(strings)/sizeof(strings[0]);

    string best_string = "foo";
    const string& string_processed = best_string;

    for_each( &strings[0], &strings[num_strings], [&string_processed]  (const string& s)  -> void 
    {
        string_processed = s;    // this should fail
    }
    );
    return 0;
}

But that's the same as assuming that your lambda have to be isolated from the current function, making it a non-lambda.

Solution 5 - C++

There is a shorter way.

Note that there is no ampersand before "best_string".

It will be of a const std::reference_wrapper<T> type.

[best_string = std::cref(best_string)](const string& s)
{
    best_string = s; // fails
};

http://coliru.stacked-crooked.com/a/0e54d6f9441e6867

Solution 6 - C++

I think you have three different options:

  • don't use const reference, but use a copy capture
  • ignore the fact that it is modifiable
  • use std::bind to bind one argument of a binary function which has a const reference.

using a copy

The interesting part about lambdas with copy captures is that those are actually read only and therefore do exactly what you want them to.

int main() {
  int a = 5;
  [a](){ a = 7; }(); // Compiler error!
}

using std::bind

std::bind reduces the arity of a function. Note however that this might/will lead to an indirect function call via a function pointer.

int main() {
  int a = 5;
  std::function<int ()> f2 = std::bind( [](const int &a){return a;}, a);
}

Solution 7 - C++

Use clang or wait until this gcc bug is fixed: bug 70385: Lambda capture by reference of const reference fails [https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70385]

Solution 8 - C++

Using a const will simply have the algorithm ampersand set the string to it's original value, In other words, the lambda won't really define itself as parameter of the function, though the surrounding scope will have an extra variable... Without defining it though, it wouldn't define the string as the typical [&, &best_string](string const s) Therefore, its most likely better if we just leave it at that, trying to capture the reference.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn DiblingView Question on Stackoverflow
Solution 1 - C++Piotr SkotnickiView Answer on Stackoverflow
Solution 2 - C++Steve MView Answer on Stackoverflow
Solution 3 - C++zhbView Answer on Stackoverflow
Solution 4 - C++KlaimView Answer on Stackoverflow
Solution 5 - C++Sergey PalitsinView Answer on Stackoverflow
Solution 6 - C++Alexander OhView Answer on Stackoverflow
Solution 7 - C++user1448926View Answer on Stackoverflow
Solution 8 - C++SaithView Answer on Stackoverflow