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. Pass by-value if sizeof(T) <= sizeof(void*)
, if T
is a fundamental type, or if the cost of copying a T
is high (as is that case of string
, or vector
, or generally any container).
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.
No.
I am curious what application are you thinking of where it could possibly be considered?