Reputation: 4779
I have this striped-down example of a timer that I'd like to be instantiable with any kind of callable. Is it advisable to precautionary move the callable into a data member for efficiency?
#include <concepts>
#include <cstdio>
#include <string>
#include <utility>
template <std::invocable Cb>
class timer {
public:
timer(Cb cb)
: cb_ { std::move(cb) }
{
}
auto call()
{
cb_();
}
private:
Cb cb_;
};
int main()
{
std::string something_to_print = "Hello World!\n";
timer some_timer([&]() { printf(something_to_print.c_str()); });
some_timer.call();
return 0;
}
I can't see any difference in the assembly if I move or copy the lambda. Does it ever make a difference?
Upvotes: 2
Views: 62
Reputation: 34636
Your lambda has only reference captures. Moving an lvalue-reference does exactly the same as copying it. If you had [=]
captures, the move would actually do something.
The answer to whether or not to do this in general is: "it depends on the situation." W.r.t. performance: measure.
Upvotes: 5