谓词 lambda 上的 `std::move` 是什么意思?

问题描述 投票:0回答:1

我正在阅读https://en.cppreference.com/w/cpp/thread/condition_variable/wait_for并且有一行:

return wait_until(lock, std::chrono::steady_clock::now() + rel_time, std::move(stop_waiting));

如何理解

std::move
,或者更确切地说,它可以防止什么?

第二个注释,页面上说

return wait_until(..
相当于
wait_for
。真的有
return
吗?或者它们是否意味着两个函数的简单、直接等价,隐式引用它们在参数列表中创建的绝对时间点?

c++ thread-safety condition-variable
1个回答
0
投票

谓词可以是复制成本高昂的对象。这是一个例子:

std::vector<std::string> v(1'000'000); // A large vector

... // Fill the vector with actual data

// The vector is then moved inside the predicate closure object.
// This avoids the copy of the vector.
auto predicate = [v = std::move(v)](std::string s) -> bool {
    return s == v[2];
};

// Pass the predicate by move, so that the vector is not copied.
some_predicate_using_function(std::move(predicate));

现在,如果

some_predicate_using_function
复制其谓词参数,则会复制向量,这是低效的。再次使用
std::move
可以防止该复制。

此外,闭包甚至可能根本不支持复制,例如,当它捕获像

unique_ptr
这样无法复制的类型时。

出于这些原因,使用谓词对象的函数应尽可能避免复制。 (一般情况下也是如此:处理未知、可能较大或不可复制对象的模板函数应避免复制。)

© www.soinside.com 2019 - 2024. All rights reserved.