Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a default value to a reference for a std::string ?

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

like image 579
Stefano Borini Avatar asked Nov 06 '13 09:11

Stefano Borini


People also ask

Is string passed by reference in C++ by default?

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.

Is std :: string passed by reference?

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

What is the default value of std :: string?

The particular case of the default default value because a default constructed std::string is an empty string.

What is the default value for a set in C++?

The default constructor with argument has a default parameter x, which has been assigned a value of 0.


1 Answers

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.

like image 75
billz Avatar answered Sep 29 '22 10:09

billz