How to save and pass std :: function

I am having trouble understanding when to pass / store std :: function objects by value or reference, or if I need to use the move semantics somehow. I have a structure that stores two std :: function:

struct Control{ char key; std::function<void()> press; std::function<void()> release; Control(char key, std::function<void()> press, std::function<void()> release): key(key),press(press),release(release){} } 

I also have a class that contains a vector of these structures, and I would like to initialize it in a function like this:

 void Screen::init(Player& player){ this->controls.push_back(Control( 'W', [&player](){player.go(UP);}, [&player](){player.stop(UP);})); } 

I would like to be able to pass lambda expressions directly to the Control constructor and eventually do this several times:

 void Screen::update(){ foreach (auto control : controls){ if(...) control.press(); else if (...) control.release(); } } 

I came across a lot of errors and crashes trying to implement this idea, so I need to know

  • Should std :: functions be stored by reference (const?) Or by value, taking into account that they fix the link?
  • Should they be passed to the Control constructor using a (const?) Reference or value (or moved in some way)?
  • Is it good to store controls by value in a vector this way, or do I need to use an alternative (unique_ptr, etc.)?
  • when I look at a control vector, should I access them by value or by reference?

Suppose that the Player & object is always in the scope of Screen :: update ()

+7
source share

All Articles