【发布时间】:2020-06-06 19:53:37
【问题描述】:
我有一个工厂方法返回 std::function
class Builder {
public:
function<void(Data&)> build();
}
和一个仿函数对象
class Processor {
protected:
vector<int> content_;
public:
void operator()(Data&) {
....
}
}
现在我想在工厂方法中返回函子,我写
function<void(Data&)> build() {
Processor p;
// Add items to p.content_
function<void(Data&)> ret(p);
return ret;
}
我的问题是:ret 会保留一份p 的副本吗?如果是这样,当p.content_ 很大时,这会成为负担吗?建议的实现方式是什么?
【问题讨论】:
-
使用
void operator()(Data&&)和function<void(Data&)> ret(std::move(p));。您需要为Processor类实现移动构造函数(还记得规则 5)。 -
嗯.. 合成的移动 ctor 不应该足够吗?零法则!不过,您确实需要返回
std::move(ret) -
@AsteroidsWithWings 从本地移动返回 is implicit。
-
你的代码写得很好(假设你不介意
Processor被复制)。事实上,ret复制了p。您可以使用function<void(Data&)> ret(std::move(p))来移动它 -
@AsteroidsWithWings 我很确定返回值优化会照顾到
std::move(ret)。
标签: c++ functor std-function