相关疑难解决方法(0)

Lambda捕获为const引用?

是否可以通过lambda表达式中的const引用进行捕获?

我希望下面标记的作业失败,例如:

#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";

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

更新:由于这是一个老问题,如果C++ 14中有设施来帮助解决这个问题,那么更新它可能会更好.C++ 14中的扩展是否允许我们通过const引用捕获非const对象?(2015年8月)

c++ lambda c++11 c++14

151
推荐指数
6
解决办法
5万
查看次数

标签 统计

c++ ×1

c++11 ×1

c++14 ×1

lambda ×1