void doStuff( std::string const & s1, std::string const & s2="");
I was wondering if this code is legal in C++, for the s2 string. I want to have a default argument, but passing a reference and having an empty string as default. Will a temporary be created, and the reference will point to that temporary, or is it illegal C++?
C++ string objects are passed and returned by value by default. This results in a copy of the string object being created. To save memory (and a likely call to the copy constructor), a string object is usually passed by reference instead.
Passing it in by reference is preferable: (std::string &) 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 &&)
The particular case of the default default value because a default constructed std::string is an empty string.
The default constructor with argument has a default parameter x, which has been assigned a value of 0.
Yes this is legal. const
will ensure temporary be lasting till function doStuff
finishes.
§ 12.2.5
A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.
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