Passing std::string by Value or Reference

Nordlöw picture Nordlöw · May 28, 2012 · Viewed 121.9k times · Source

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)?

Answer

linuxuser27 picture linuxuser27 · May 28, 2012

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 &&)