【发布时间】:2021-03-08 08:47:43
【问题描述】:
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调用不能编译。
为什么?感谢您提供更多详细信息。
【问题讨论】:
-
Lambda 默认为
const。您需要将其显式标记为mutable-auto testaaa = [testGetStr]() mutable {...}。或者,最好将getString()标记为const。