Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing std::string by Value or Reference [duplicate]

Possible Duplicate:
Are the days of passing const std::string & as a parameter over?

Should I pass std::string by value or by reference (to a un-inlined function) if move semantics is supported? And what about implementations using small string optimization (SSO)?

like image 736
Nordlöw Avatar asked May 28 '12 19:05

Nordlöw


People also ask

Should you pass std :: string by reference?

I believe the normal answer is that it should be passed by value if you need to make a copy of it in your function. Pass it by const reference otherwise.

How do you pass a string by reference in C++?

Your code works as expected. &filename returns the memory address of (aka a pointer to) filename , but startup(std::string& name) wants a reference, not a pointer. References in C++ are simply passed with the normal "pass-by-value" syntax: startup(filename) takes filename by reference.

Why do we pass string as an reference in C++?

The passing by reference enables a function to update a variable without creating a copy. We must declare reference variables so that the parameter and variable are passed to share the same memory location. Any changes that occur in the parameter also affect the variable.

Does passing by reference make a copy?

In pass by reference (also called pass by address), a copy of the address of the actual parameter is stored.


Video Answer


1 Answers

There are multiple answers based on what you are doing with the string.

1) Using the string as an id (will not be modified). Passing it in by const reference is probably the best idea here: (std::string const&)

2) Modifying the string but not wanting the caller to see that change. Passing it in by value is preferable: (std::string)

3) Modifying the string but wanting the caller to see that change. Passing it in by reference is preferable: (std::string &)

4) Sending the string into the function and the caller of the function will never use the string again. Using move semantics might be an option (std::string &&)

like image 163
linuxuser27 Avatar answered Sep 26 '22 00:09

linuxuser27