Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing C++ strings by value or by reference

Tags:

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

like image 947
Anonymous Avatar asked Dec 11 '09 04:12

Anonymous


People also ask

Are strings passed by value or reference in C?

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.

Are strings passed by value or reference?

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.

Can strings be passed by reference?

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++.

Are C functions pass-by-reference?

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.


1 Answers

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)

like image 200
GManNickG Avatar answered Sep 19 '22 17:09

GManNickG