class TestGetStr {
public:
string a;
string getString() {
return a;
}
};
void acceptConstString(const string & a) {
std::cout << a << std::endl;
}
int main(int argc, const char * argv[]) {
auto testGetStr = TestGetStr();
acceptConstString(testGetStr.getString()); //compile ok
auto testaaa = [testGetStr](){
//compile error 'this' argument to member function 'getString' has type 'const TestGetStr', but function is not marked const
acceptConstString(testGetStr.getString());
};
普通调用和 lambda 捕获之间的区别?
普通调用可以编译,但是lambda调用无法编译。
为什么?感谢您提供更多详细信息。
最佳答案
您可以添加mutable
限定符。
auto testaaa = [testGetStr]() mutable {
// ^^^^^^^
acceptConstString(testGetStr.getString());
};
否则lambda的operator()
是 const 限定的,然后不能在捕获的对象上调用非常量成员函数。
- mutable: allows body to modify the objects captured by copy, and to call their non-const member functions
Unless the keyword
mutable
was used in the lambda-expression, the function-call operator is const-qualified and the objects that were captured by copy are non-modifiable from inside thisoperator()
.
PS:或者更好地使 TestGetStr::getString()
const 成员函数。
关于C++ lambda 按值语义捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66526702/