c++ - B. Stroutstrup 在他的新书 "incautious use"第 4 版的第 296 页上的这一段中用表达式 "TCPL"指的是什么?

标签 c++ c++11 lambda

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 through this 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 可能会令人惊讶。 正在捕获指向对象的指针,而不是捕获 opervalues 的拷贝。

隐式泄漏指针/引用并将它们散布在多线程代码中是导致灾难性 UB 的秘诀。该标准没有定义具有数据竞争的程序的行为:多个线程可能同时访问一个内存位置(对象),至少其中一个执行写入。

关于c++ - B. Stroutstrup 在他的新书 "incautious use"第 4 版的第 296 页上的这一段中用表达式 "TCPL"指的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21565586/

相关文章:

c++ - C++11 中的元组有哪些好的用例?

c++ - 浮点值 0.0 的表示方式是否与其他浮点值不同?

c++ - 在不改变缩进的情况下重新格式化 C++ 大括号?

c++ - 将内联函数作为参数传递

lambda - 从Kendo UI网格中创建具有相关对象的表达式[FilterDescriptor]

c++ - `constexpr`、 `static_assert` 和 `if constexpr(...)` 变量之间的模板中 `constexpr` lambda 的评估不一致

c++ - 16 位音频的 fftw::peak 在 2f 出现错误

c++ - 为什么我的程序在这一行崩溃了?

c++ - 如何在类中初始化 C++11 native 指针和数组?

java - 过滤时 lambda 表达式中的空值在 Java 中出现异常