【问题标题】:How to move a variable into a lambda expression?如何将变量移动到 lambda 表达式中?
【发布时间】:2015-05-13 18:22:41
【问题描述】:

我看到了 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 的任何内容(即,我想确保这不会与 @ 发生冲突987654328@ 或类似的不良结果)。
  2. 如果第一个问题的答案是“您不能在捕获的引用上使用std::move”,那么正确的做法是什么(例如,std::bind 解决方案等)?

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    使用闭包是否等同于直接调用bar函数的代码?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-11
      • 1970-01-01
      • 2014-02-20
      • 2017-04-21
      • 2013-09-10
      相关资源
      最近更新 更多