考虑以下:
void test( const int &value )
{
auto testConstRefMutableCopy = [value] () mutable {
value = 2; // compile error: Cannot assign to a variable captured by copy in a non-mutable lambda
};
int valueCopy = value;
auto testCopyMutableCopy = [valueCopy] () mutable {
valueCopy = 2; // compiles OK
};
}
Run Code Online (Sandbox Code Playgroud)
当我将lambda声明为可变并按value值捕获时(为什么我认为它是副本),为什么第一个版本是编译错误?
使用clang(x86_64-apple-darwin14.3.0)进行测试,这是错误消息的来源,以及Visual C++(vc120).
前提#1:我已经解决了错误,但我没有深入理解编译错误的原因.
前提#2:该程序的目标是通过多线程进程将图像复制到另一个图像中.也许存在更好的方法,但这不是问题的焦点话题(见前提#1).
我用OpenCV 3.1库编写了一个简单的程序,将图像复制到另一个图像中.它利用了更多线程的CPU的所有核心.
代码是:
#include <opencv2/opencv.hpp>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <thread>
using namespace cv;
using namespace std;
#define IMG_PATH "..\\img\\50a.png"
void copy_image(const Mat& input, Mat& output, int row_offset, int skip_row)
{
cout << row_offset;
Size size = input.size();
for (int r = row_offset; r < size.height; r += skip_row)
{
for (int c = 0; c < size.width; c++)
{
output.at<Vec3b>(r, c) = input.at<Vec3b>(r, c);
}
}
}
int main()
{
Mat input_img = …Run Code Online (Sandbox Code Playgroud) 我打算用C++编写一个记忆模式,最后采用以下方法
std::function<int(int)> Memoize(std::function<int(int)> fn)
{
std::map<int, int> memo;
std::function<int(int)> helper = [=](int pos)
{
if (memo.count(pos) == 0)
{
memo[pos] = fn(pos);
}
return memo[pos];
};
return helper;
}
Run Code Online (Sandbox Code Playgroud)
奇怪的是,我的编译器VS 2012,拒绝编译时出现以下错误
1>Source1.cpp(24): error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<_Kty,_Ty>' (or there is no acceptable conversion)
Run Code Online (Sandbox Code Playgroud)
在我看来,编译器故意通过值捕获所有内容作为const对象.我找不到任何有关此行为的文档参考.
任何人都可以帮助我理解这里可能发生的事情吗?