خرید بک لینک

Vote count: 1

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 conceed about achieving maximum performance.

b. If I am conceed 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.

asked 10 mins ago

2 Answers

Vote count: 0

You can accept it by value and have the caller invoke std::move() on the argument. This way the callee gets its own copy and the caller can decide whether to copy or move.

Accepting by r-value or non-const reference, though, saves from calling the move constructor. In other words, if you are minimizing the number of instructions executed then accept the string by a reference.

answered 5 mins ago

Vote count: 0

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.

That's not true, only if you pass the string by value, then a copy is created. A const& is just like a &, but it guarantees that the function will not modify the variable.

I would suggest using the const reference way, because it doesn't invoke the copy or move constructor, and so is the fastest way, out of all three.

The only downfall is that you would have to copy the string in the function if you want to modify it, but if you do that, better let the compiler do it for you and pass by value.

answered just now

برچسب: نویسنده: استخدام کار تاريخ: چهارشنبه 5 خرداد 1395 ساعت: 23:40

صفحه بندی