I'm wondering whether the C++ string is considered small enough to be more efficient when passed by value than by reference.
If the function needs to modify a dynamically allocated (i.e. heap-allocated) string buffer from the caller, you must pass in a pointer to a pointer. In C, function arguments are passed by value. This means that to modify a variable from within a function, you need a pointer to the variable.
All arguments in Java are passed by value. When you pass a String to a function, the value that's passed is a reference to a String object, but you can't modify that reference, and the underlying String object is immutable.
Pass String by Reference in C++ The C++ reference is a name for a variable that already exists. A reference to a variable can't be altered to refer to the other variable once initialized. Pointers or references can be passed as parameters to functions in C++.
Pass by Reference A reference parameter "refers" to the original data in the calling function. Thus any changes made to the parameter are ALSO MADE TO THE ORIGINAL variable. Arrays are always pass by reference in C.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With