c++ - 如何将变量移动到 lambda 表达式中?

标签 c++ c++11

我看到 C++11 文档 ( http://en.cppreference.com/w/cpp/language/lambda ) 的 lambda 表达式状态支持按值和引用捕获,但不支持右值引用。我能找到的与此相关的最接近的 SO 问题是:How to capture a unique_ptr into a lambda expression? ,但我的用例似乎不需要使用 std::bind

代码

#include <iostream>
#include <memory>

class Foo
{
public:
    explicit Foo(int value = 0) : mValue(value) {}

    // The following items are provided just to be explicit
    Foo(Foo &&other) = default;
    Foo &operator=(Foo &&other) = default;
    Foo(const Foo &other) = delete;
    Foo &operator=(const Foo &other) = delete;
    ~Foo() {}

    int mValue;
};

void bar(std::unique_ptr<Foo> f)
{
    std::cout << "bar:  " << std::dec << f->mValue << "\n";
}

int main()
{
    {
        std::unique_ptr<Foo> f(new Foo(22));
        std::cout << "main: " << std::hex << f.get() << "\n";

        // Call the bar function directly (requires using std::move)
        bar(std::move(f));
        std::cout << "main: " << std::hex << f.get() << "\n";
    }

    {
        std::unique_ptr<Foo> f(new Foo(99));
        std::cout << "main: " << std::hex << f.get() << "\n";

        // Lamda expression captures 'f' by reference and then calls the bar function (again, requires using std::move)
        auto fn = [&f](){ bar(std::move(f)); };
        fn(); // Execute the closure
        std::cout << "main: " << std::hex << f.get() << "\n";
    }

    return 0;
}

示例输出

main: 0x92e010
bar:  22
main: 0
main: 0x92e010
bar:  99
main: 0

通过检查输出,似乎该程序正确运行(即,观察到的结果是我所期望的。但是,我有以下问题。

问题

  1. 使用闭包是否等同于直接调用bar函数的代码?
    • 我明确地询问,因为关于 lambda 表达式的文档(参见问题的开头)没有说明关于在捕获的引用上使用 std::move 的任何内容(即,我想确保这不会与 undefined behavior 或类似的不良结果发生冲突。
  2. 如果第一个问题的答案是“您不能在捕获的引用上使用 std::move”,那么正确的方法是什么(例如, std::bind 解决方案等)?

最佳答案

Is using the closure equivalent to the code that calls the bar function directly?

是的,它们在这段代码中是等价的。捕获的引用在我能想到的任何方面都不是特别的:你有完全定义的行为,只要 f 在范围内并且可以从中移动。

关于c++ - 如何将变量移动到 lambda 表达式中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28995481/

相关文章:

c++ - 使用 strtok 拆分 C 字符串

c++ - rand() 有某种数值限制吗?

c++ - Visual Studio 2013 在/OPT :ICF? 存在的情况下是否正确优化

c++ - 生成器模式 : making sure the object is fully built

c++ - 无法在 Solaris 的最新编译器中将 xercesc 与新的 c+11 标志一起使用

c++ - C++中具有相同名称但成员不同的结构

c++ - 从其他专门函数调用专门函数

c++ - 检查当前文件是否为 doc、docx、xls、xlsx 或 pdf 格式

c++ - 使用 OpenCV 工具从连续的图像差异中检测国际象棋走法

c++ - 除了模拟测试之外,无需额外使用接口(interface)即可编码到接口(interface)?