c++11 按值捕获 lambda 产生错误的值

标签 c++ c++11

我试图将 lambda 存储在涉及多层间接的对象系统中。我正在使用 g++ 4.7.1。

根据我构造(等效)对象的精确方式,lambda 可能有也可能没有正确的值。

代码:

#include <iostream>
#include <functional> // used for std::function

using namespace std; // TODO nope

typedef function<int()> intf;


struct SaveLambda {
    const intf func;
    SaveLambda(const intf& _func) : func(_func) {}  
};


struct StoreSaved {
    const SaveLambda* child;
    StoreSaved(const SaveLambda& _child) : child(&_child) {
        cout << "Before returning parent: " <<  child->func() << endl;
    }
};


int main() {
    const int ten = 10;

    auto S = SaveLambda([ten](){return ten;});
    cout << "No indirection: " << S.func() << endl << endl;

    auto saved = StoreSaved(S);
    cout << "Indirection, saved: " << saved.child->func() << endl << endl;

    auto temps = StoreSaved ( SaveLambda([ten](){cout << "&ten: "<< &ten << endl; return ten;}) );
    cout << "***** what. *****" << endl;
    cout << "Indirection, unsaved: " << temps.child->func() << endl;
    cout << "***** what. *****" << endl << endl;

    cout << "ten still lives: " << ten << endl;
}

编译为 g++ -std=c++11 -Wall -o itest itest.cpp 并运行:注意输出的一行具有不同的值。

我做错了什么?我认为按值(value)捕获将会按值(value)捕获。 (最令人不安的是,StoreSaved 中的打印(第 15 行)产生了正确值,与第 34 行不同,尽管它们都引用同一个对象。唯一的区别是添加了另一层间接层。)

最佳答案

这是错误的:

auto temps = StoreSaved(
                /* This temporary value dies at the last semicolon! */
                SaveLambda([ten](){cout << "&ten: "<< &ten << endl; return ten;})
                );

StoreSaved 然后有一个指向不存在的对象的指针。使用它就是UB。

关于c++11 按值捕获 lambda 产生错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12273249/

相关文章:

c++ - 使用 unordered_map 确定子数组索引失败的函数

c++ - 何时使用 weak_ptr 而不是引用调用

c++ - 在 visual studio 2008 中检查编译器版本

c++ - 使用成员函数时使用 std::result_of 编译失败

c++ - 慢多集的 vector 版本

c++ - 做什么 ({});在 C++ 中是什么意思?

c++ - 从 std::array 获取对原始数组的引用

c++ - 同一模板类中的友元

c++ - 在精神上使用语义 Action 和属性传播

c++ - 在简单的 C++ OpenCV 项目中使用 pthread