gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:09:30 24 4
gpt4 key购买 nike

我看到 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com