I have a piece of code that requires passing a function object (functional). I can’t use function pointers because I need to store some state variables. Let’s say I have quite a few state variables. Is it ok to pass the function object by reference? I’ve only seen function objects passed by value. This is what my code will look like:
struct FunctionObject {
double a, b, x, y;
double operator() (int v, int w) {....}
};
template <class T>
Class MyClass {
T& func;
.....
public:
MyClass(T& func):func(func) {}
.....
};
Passing function objects by reference is fine, but you should be aware that many C++ algorithms copy function objects, so if you need a library algorithm to respect your state you should pass it as a reference inside your function object:
Also, some library algorithms (e.g.
transform) require pre-C++11 that the function object have no side effects i.e. no state whatsoever; this requirement is rarely enforced and is relaxed in C++11.