Home >Backend Development >C++ >Should We Still Pass `std::string` by `const std::string&` Reference?
The Obsolescence of Passing const std::string& References: Herb Sutter's Perspective
In a recent talk, Herb Sutter expressed the diminishing relevance of passing std::vector and std::string by const&. He suggested that the traditional approach:
std::string do_something(const std::string& inval)
is now less desirable compared to:
std::string do_something(std::string inval)
While it's acknowledged that inval retains its size, Herb's argument stems from scenarios involving function chaining. Consider the example where A calls B, which in turn calls C:
Case 1: Passing by const Reference
void B(const std::string& str) { C(str); } void C(const std::string& str) { /* Use str but do not store it */ }
When C requires storage, a copy operation becomes necessary:
void C(const std::string& str) { m_str = str; }
However, the use of const& prevents C from accessing the underlying data moved into its parameter.
Case 2: Passing by Value
void B(std::string str) { C(std::move(str)); } void C(std::string str) { m_str = std::move(str); }
In this scenario, the string is moved through the function calls, avoiding unnecessary copies. The performance overhead of moving into a value is offset by the benefits of avoiding memory allocations for small strings with Short String Optimization (SSO).
Ultimately, the choice between passing by const reference or value depends on the specific use case and the developer's preference for memory allocation efficiency versus potential performance drawbacks.
The above is the detailed content of Should We Still Pass `std::string` by `const std::string&` Reference?. For more information, please follow other related articles on the PHP Chinese website!