If there is any possibility you are storing a copy of the std::function , pass by value. Otherwise, either way is roughly equivalent: the only downside to by-value is if you are taking the same bulky std::function and having one sub method after another use it. Barring that, a move will be as efficient as a const& .
I believe the normal answer is that it should be passed by value if you need to make a copy of it in your function. Pass it by const reference otherwise.
strings are passed by reference. The built in string type is a value type.
Instances of std::function can store, copy, and invoke any CopyConstructible Callable target -- functions, lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.
I'm having trouble knowing when to pass/store std::function objects by value or reference, or if I need to use move semantics somehow. I have a struct that stores two std::function
objects:
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 structs, and I'd like to initialize it in a function resembling this one:
void Screen::init(Player& player){
this->controls.push_back(Control(
'W',
[&player](){player.go(UP);},
[&player](){player.stop(UP);}));
}
I'd like to be able to pass lambda expressions directly to the Control constructor, and eventually do this repeatedly:
void Screen::update(){
foreach (auto control : controls){
if(...)
control.press();
else if (...)
control.release();
}
}
I've encountered a lot of errors and crashes trying to implement this idea, so I need to know
std::function
's be stored by (const?) reference, or by value, taking into account they capture a reference?unique_ptr<Control>
, etc.)?Assume that the Player&
object is always in scope for Screen::update()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With