tags:

views:

182

answers:

3

I'm wondering whether the C++ string is considered small enough to be more efficient when passed by value than by reference.

+12  A: 

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)

GMan
Your heuristic doesn't work for `double` and `long double` (which are normally better off being passed by value). As well, for single-argument functions, it's normally better to pass 2 x machine word UDTs by value, as registers will be used to store both parts (and save an extra indirection).
Pavel Minaev
Furthermore, `sizeof(T)` is a very poor measure in general if only because it doesn't measure the true size of data that will be copied. `string` is a particularly good example of that, as `sizeof(string)` will typically be `sizeof(void*)` on a naive implementation (a simple pointer to data), or two or three words on short-string optimizing implementation. Yet, when you copy a string, its copy constructor will copy the data being pointed to, which is unaccounted for. Same goes for `vector`, and many other.
Pavel Minaev
How's that​​​​​?
GMan
I personally prefer the following heuristic: built-ins by value, anything that has a copy-constructor by const reference.
Matthieu M.
+1  A: 

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.

Drew Hall
A: 

No.

I am curious what application are you thinking of where it could possibly be considered?

mobibob