You have a few options to pass variables in C++
1) By value
void foo(std::string value) { /* ... */ }
// ... call
foo(data);
The copy constructor of std::string
is used to create a local instance in foo
and modifications stay in the local instance.
2) By reference
void foo(std::string &value) { /* ... */ }
// ... call
foo(data);
The parameter variable is referenced, so value
in foo
is pointing to the same object that you pass to the function. Changes are reflected in your calling code.
3) By const reference
void foo(const std::string &value) { /* ... */ }
// ... call
foo(data);
As in (2) the parameter object is referenced rather than creating a new instance. However, the contract is not to modify your value
inside foo
. This may be cheaper in terms of memory and performance than (1) where the whole string is copied.
4) By pointer
void foo(std::string *value) { /* ... */ }
// ... call
foo(&data);
You pass the adress of data
as parameter to foo
. It is similar to a reference, just relying on pointer logic. In order to access the string in value
, you have to dereference the pointer as in (*value)
or value->some_string_function()
5) By pointer to constant object
void foo(const std::string *value) { /* ... */ }
// ... call
foo(&data);
Similar to (4), but the object that the pointer is referencing is constant like in the reference case (3). Note that the pointer itself is not constant, so it is possible to point it to a different object. However, the pointer is local (the object pointed to is not local though), so changing the pointer adress inside foo
has no effect on the data
object.