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)?
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.
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.
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.
In pass by reference (also called pass by address), a copy of the address of the actual parameter is stored.
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 &&)
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