[英]C++ Return a functor object as std::function
I have a factory method returning a std::function
我有一个工厂方法返回一个
std::function
class Builder {
public:
function<void(Data&)> build();
}
and a functor object和一个函子 object
class Processor {
protected:
vector<int> content_;
public:
void operator()(Data&) {
....
}
}
Now I want to return the functor in the factory method, and I write现在我想在工厂方法中返回函子,我写
function<void(Data&)> build() {
Processor p;
// Add items to p.content_
function<void(Data&)> ret(p);
return ret;
}
My question is: will ret
maintain a copy of p
?我的问题是:
ret
会保留p
的副本吗? If so, when p.content_
is large, will that become a burden?如果是这样,当
p.content_
很大时,这会成为负担吗? What will be a suggested way to implement this?建议的实施方式是什么?
A std::function
hold and own its value.一个
std::function
持有并拥有它的价值。 In fact, it requires callable object that are copiable so it can copy it when itself is copied.实际上,它需要可复制的可调用 object,以便在复制自身时可以复制它。
Your function would be perfectly fine like this, and potentially faster:您的 function 会像这样非常好,并且可能更快:
function<void(Data&)> build() {
Processor p;
// fill items
return p; // p moved into the returned std::function (since C++14)
}
However, if you copy the std::function
around, the Processor
object will be copied too, so the cost of copying the std::function
depends on the type it contains (just as with any type erasure tools)但是,如果您复制
std::function
周围, Processor
object 也会被复制,因此复制std::function
的成本取决于类型(就像它包含的任何类型擦除工具一样)
The constructor that will be used is this :将使用的构造函数是这样的:
template< class F >
function( F f );
You can see that the object will be copied.可以看到 object 会被复制。 If you want to avoid this, you can move the callable:
如果你想避免这种情况,你可以移动可调用对象:
function<void(Data&)> ret(std::move(p));
The constructor will then move f
to the internal storage.然后构造函数将
f
移动到内部存储。
If your callable is small, it will be stored directly in the function object.如果您的可调用对象很小,它将直接存储在 function object 中。 If it is too large, the internal storage will be allocated dynamically.
如果太大,内部存储将被动态分配。 Either way, moving resulting function object should be no more complex than moving the original callable object (when stored directly in the function) or probably even cheaper (when stored dynamically).
无论哪种方式,移动生成的 function object 应该不会比移动原始的可调用 object 复杂(当直接存储在函数中时)甚至可能更便宜(当动态存储时)。
Copying should be avoided when performance is important, as it might involve dynamic allocations even if your callable doesn't need them.当性能很重要时,应避免复制,因为即使您的可调用对象不需要它们,它也可能涉及动态分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.