默认情况下,lambda 的 operator() 是 const 成员函数,意味着在 lambda 体内不能修改通过值捕获的捕获变量。因此如果想要修改捕获的变量,需要使用mutable。
#include <iostream>
#include <string>
using namespace std;
class T{
public:
T() {
cout << "T()" << endl;
}
T(const T&) {
cout << "T(const T&)" << endl;
}
T(T&& t) {
cout << "T(T&&)" << endl;
str = std::move(t.str);
}
~T() {
cout << "~T()" << endl;
}
string str;
};
void func()
{
T t1;
t1.str = "Hello, World!";
auto lambda = [t = std::move(t1)]() mutable {
cout << "Inside lambda: " << t.str << endl;
t.str = "Modified inside lambda";
订阅专栏 解锁全文
1万+

被折叠的 条评论
为什么被折叠?



