Comment by cherryteastain
Comment by cherryteastain 6 months ago
In this function
void Call(T arg) const {
if (fn) {
fn(userData, arg);
}
}
Say you pass something like an std::vector<double> of size 1 million into Call. It'll first copy the std::vector<double> at the point you invoke Call, even if you never call fn. Then, if fn is not nullptr, you'll then copy the same vector once more to invoke fn. If you change Call instead to void Call(T&& arg) const {
if (fn) {
fn(userData, std::forward<T>(arg));
}
}
the copy will not happen at the point Call is invoked. Additionally, if arg is an rvalue, fn will be called by moving instead of copying. Makes a big difference for something like std::vector<double> foo();
void bar(Func1<std::vector<double>> f) {
auto v = foo();
f(std::move(v));
}