Is it possible to pass objects to functions by reference?

I have a piece of code that requires passing a functional object (functional). I cannot use function pointers because I need to save some state variables. Let's say I have quite a few state variables. Is it possible to pass an object to a function by reference? I saw only function objects passed by value. This will look like my code:

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) {} ..... }; 
+4
source share
4 answers

Passing object objects by reference is fine, but you should know that many C ++ algorithms copy function objects, so if you need a library algorithm to respect your state, you must pass it as a link inside your function object:

 struct State { double a, b, x, y; }; struct Function { State &state; explicit Function(State &state): state(state) {} double operator() (int v, int w) {....} }; State state; std::...(..., Function(state), ...) 

In addition, some library algorithms (e.g. transform ) require pre-C ++ 11 that the function object has no side effects, i.e. no state at all; this requirement is rarely applied and mitigated in C ++ 11.

+4
source

This mainly depends on how you intend to initiate the FunctionObject (how you create the function objects). If you use links, you must make sure that the function object survives the user object (MyClass).

For instance:

 MyClass* createObject() { MyFunction f(...); // function object created return new MyClass(f); // reference used // function object destroyed => reference invalid } 

incorrect because the returned object has a reference to the destroyed (invalid) function.

Since you get very little by clicking on the link (without copying a small object), this is not a hassle (checking the life of objects) and the risk of oversight (error)

+1
source

The syntax is correct, but ...

  • most of the time you are going to call the function object later in your code, so you need to make sure that the link you provided in MyClass is still in scope
  • so in the end, since you need to save the function object in the heap skewer than the stack, you have to create a pointer to it ... so I recommend using a pointer ...
0
source

Function objects are objects. You can pass them by reference, and you can store links to them depending on ordinary life problems. However, the algorithms in std:: allow you to make copies of your functional objects whenever they want, so any stored state can be outdated, so it's better to write a function object as a wrapper around the pointer or a link to its state.

0
source

Source: https://habr.com/ru/post/1446035/


All Articles