当我使用[=]捕获(使用Lambda类)时,为什么变量变成'const'? [英] Why does a variable become 'const' when I use a [=] capture (using Lambda class)?
问题描述
前提#1 :我已经解决了该错误,但是我不十分了解编译器错误的原因.
Premise #1: I have already solved the error, but I didn't deeply understand the cause of the compiler error.
前提2 :该程序的目标是通过多线程进程将一个映像复制到另一个映像中.也许存在更好的方法,但这不是问题的重点(请参阅前提1).
Premise #2: The goal of this program is to copy a image into another image by a multithreaded process. Maybe a better way exists, but this is not the focus topic of the question (see premise #1).
我使用OpenCV 3.1库编写了一个简单程序,可以将一个图像复制到另一个图像中.它利用了使用更多线程的CPU所有内核.
I wrote a simple program using OpenCV 3.1 library to copy a image into another image. It takes advantage of all cores of the CPU using more threads.
代码是:
#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 = imread(IMG_PATH);
Mat output_img = Mat(input_img.size(), input_img.type()); output_img.setTo(255);
vector<thread> threads;
int thread_number = thread::hardware_concurrency();
for (int i = 0; i < thread_number; i++)
{
cout << i;
auto var = [=]()
{
return copy_image(input_img, output_img, i, thread_number);
};
threads.push_back(thread(var));
}
for (auto& thread : threads)
thread.join();
imshow("output_img", output_img);
imwrite("result.png", output_img);
waitKey(0);
}
编译器向我返回此错误
错误C2664'无效的copy_image(const cv :: Mat&,cv :: Mat&,int,int)': 无法将参数2从'const cv :: Mat'转换为'cv :: Mat&'
Error C2664 'void copy_image(const cv::Mat &,cv::Mat &,int,int)': cannot convert argument 2 from 'const cv::Mat' to 'cv::Mat &'
它使用以下代码行:
return copy_image(input_img, output_img, i, thread_number);
我解决了替换此行的错误
I solved this error replacing this line
auto var = [=]()
与此
auto var = [=, &input_img, &output_img]()
但实际上我不十分了解为什么收到该错误.
but actually I don't deeply understand why I received that error.
推荐答案
如果您在lambda中按值进行捕获,则将获得一个成员",该成员将被存储.由于默认的operator()
是const函数,因此无法对其进行修改.
If you do a capture by value in a lambda, you will get a 'member' which gets stored. As the default operator()
is a const function, you cannot modify them.
可以将Lambda定义为[]() mutable {}
,以允许您修改局部变量.
Lambdas can be defined as []() mutable {}
to allow you to modify the local variables.
通过按引用捕获值,您的行为就像指向非const对象的const指针一样,因此如果没有可变对象,则可以适应这些对象. (除非它们已经在const中了)
By capturing the value by reference, you have something which behaves like a const pointer to a non-const object, so without the mutable, you can adapt those objects. (Unless they already where const)
这篇关于当我使用[=]捕获(使用Lambda类)时,为什么变量变成'const'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!