class Request { function<map<string,string>(const map<string,string>&)> oper; // operation map<string,string> values; // arguments map<string,string> results; // targets public: Request(const string& s); // parse and store request void execute() { [this]() { results=oper(values); } // do oper to values yielding results } };
Members are always captured by reference. That is,
[this]
implies that members are accessed throughthis
rather than copied into the lambda. Unfortunately,[this]
and[=]
are incompatible. This implies that incautious use can lead to race conditions in multi-threaded programs (§42.4.6).
最佳答案
他试图阐明捕获this
——无论是隐式还是显式——都不会复制this
指定的对象。否则,像 [=](){ return oper(values); 这样的 lambda 可能会令人惊讶。
正在捕获指向对象的指针,而不是捕获 oper
和 values
的拷贝。
隐式泄漏指针/引用并将它们散布在多线程代码中是导致灾难性 UB 的秘诀。该标准没有定义具有数据竞争的程序的行为:多个线程可能同时访问一个内存位置(对象),至少其中一个执行写入。
关于c++ - B. Stroutstrup 在他的新书 "incautious use"第 4 版的第 296 页上的这一段中用表达式 "TCPL"指的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21565586/