Passing C++ strings by value or by reference
I'm wondering whether the C++ string is considered small enough to be more efficient when passed by value than by 开发者_如何学运维reference.
No. Pass it by reference:
void foo(const std::string& pString);
In general, pass things by-reference if they have a non-trivial copy-constructor, otherwise by-value.
A string usually consists of a pointer to data, and a length counter. It may contain more or less, since it's implementation defined, but it's highly unlikely your implementation only uses one pointer.
In template code, you may as well use const T&
, since the definition of the function will be available to the compiler. This means it can decide if it should be a reference or not for you. (I think)
Definitely not. Unless your particular implementation has copy-on-write semantics (rare these days due to threading concerns), the whole string has to be copied when it's passed by value (even if the actual string data is stored on the heap). Even if the string object itself is only a couple of pointers internally, the amount of data to be copied is linear in the length of the string.
精彩评论