Does Passing Const std::string & as a Parameter Offer Benefits Anymore?
In a recent talk, renowned C expert Herb Sutter suggested that the arguments for passing std::vector and std::string by const & are no longer compelling. To illustrate, he proposed a function written as follows:
std::string do_something ( std::string inval ) { std::string return_val; // ... do stuff ... return return_val; }
Herb reasoned that, since the return_val would be an rvalue at the time of function return, it could be returned using cost-effective move semantics. However, the question remains: why pass the input parameter inval by reference? Doesn't the larger size of a std::string object (due to components like the heap pointer and char array) make passing by value more advantageous?
Herb's Rationale
Herb's suggestion stems from scenarios where multiple nested functions are involved. Consider a situation where function A calls function B, which in turn calls function C, each passing a string parameter. If B and C take the string as a const &, the code might look like this:
void B(const std::string & str) { C(str); } void C(const std::string & str) { // Use `str` without storing it. }
This approach efficiently passes pointers around, avoiding copying or moving. C takes a const & because it does not store the string.
However, suppose C now needs to store the string. Modifying C to the following will force B to perform a copy into its parameter, negating any benefit:
void C(const std::string & str) { // ... m_str = str; }
In contrast, if str were passed by value throughout all the functions, relying on std::move to handle data movement, C could simply accept ownership of the temporary string, eliminating the need for copies.
Cost Considerations
While passing by value incurs a slight performance penalty compared to using references, it can be comparable to the cost of copying for small strings with SSO. The choice between these approaches depends on the frequency of memory allocations and the specific use case.
The above is the detailed content of Is Passing `std::string` by `const std::string&` Still Beneficial in Modern C ?. For more information, please follow other related articles on the PHP Chinese website!