Should I always pass a std::string by const reference to a function if all that is done inside that function is to copy that string? Additionally, what is the difference (perf or otherwise) between passing by value and passing by reference? As I understand, one uses operator= and the other copy constructor. Is that the case?
Should I always pass a std::string by const reference to a function if all
Share
No. If you are going to just copy the string inside of the function, you should pass by value. This allows the compiler to perform several optimizations. For more, read Dave Abraham’s “Want Speed? Pass by Value.”
No, that is not at all the case. A reference is not an object; it is a reference to an object. When you pass by value, a copy of the object being passed is made. When you pass by reference, a reference to the existing object is made and there is no copy. A good introductory C++ book will explain these basic concepts in detail. It is critical to understand the basics if you want to develop software in C++.