mercredi 25 mai 2016

Pass string parameter to callback function in C++11

Suppose I have a callback function taking a string parameter. This callback function is invoked with a string object that is no longer needed at call site, and most likely this function will need to do some string processing. What would you suggest to use for the parameter - lvalue reference, rvalue reference, or const lvalue reference, or something else?

a. If I am concerned about achieving maximum performance.

b. If I am concerned about code clarity.

std::string s;

// Way 1: lvalue reference
using CallbackType = std::function<void(std::string&)>;
CallbackType callback = processMessage; // declared elsewhere
callback(s);

// Way 2: rvalue reference
using CallbackType = std::function<void(std::string&&)>;
CallbackType callback = processMessage; // declared elsewhere
callback(std::move(s));

// Way 3: const lvalue reference
using CallbackType = std::function<void(const std::string&)>;
CallbackType callback = processMessage; // declared elsewhere
callback(s);

Way 1 seems to be the fastest (function can do string processing with the original string, avoiding any copy or move) but looks a bit confusing (people may wonder if they need to change this parameter).

Way 3 seems to be the most widely used way but is the slowest as the function will have to make a copy of passed string before processing.

Way 2 is probably in the middle by performance.

Aucun commentaire:

Enregistrer un commentaire