I have a factory returning a function for data processing
class Factory {
function<void(Data&)> build();
}
Now I am struggling whether the return type should be function<void(Data&)>
or unique_ptr<function<void(Data&)>>
. In other words, how heavy is the std function, is it okay to copy it around or is it better to manage it using a smart pointer?
std::function
uses some form of type erasure, therefore, it itself shouldn't be too big. For instance, in my experiment with GCC and libstdc++, all instances of std::function
I tried had 32 bytes: live demo. Therefore, moving std::function
objects should be relatively cheap (copying might be a different thing).
Anyway, std::unique_ptr
is still smaller (typically a size of a raw pointer), therefore, it will be moved faster at an assembly level. Whether it does matter is a matter of profiling.