Should I pass std :: function by-value or by (rvalue) -reference?

I don't quite understand what the std::function instance really contains.

How much more efficient is passing it by value or by reference?

What are the performance effects in the following examples?

by value:

 void printStats(std::function<void(const char *)> printer); . . . std::string tmp; printStats([&tmp](const char * msg){ tmp += msg; }); 

by rvalue-reference:

 void printStats(std::function<void(const char *)>&& printer); . . . std::string tmp; printStats([&tmp](const char * msg){ tmp += msg; }); 
+5
source share
1 answer

Firstly, std::function is required to avoid highlighting when the target is a function pointer std::reference_wrapper ; implementation it is recommended to avoid allocation for "small" purposes :

[...] for example, where f target is an object containing only a pointer or a reference to an object and a pointer to a member function.

This means that copying std::function , whose target is large, will include highlighting and copying the target (reference counting is not allowed, since the object may have a mutable state). However, in your particular case, the copy will be deleted, since you are calling your function with a temporary value of prvalue.

In your specific case, since you call the function immediately, you don’t have to worry about taking responsibility for its use, so it would be better to use the function via the const link. Taking it by rvalue link will cause a headache for a user who has an existing lvalue or const function reference; they would have to std::move it (in the first case) or create a temporary copy of prvalue (in the latter case).

+5
source

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


All Articles