c++stringcall-by-value

How is passing a string literal to a function handled in C++?


Consider the following piece of code:

void consumeString(std::string str){
  /* some code */
}

void passStringObject(){
  std::string stringObject = "string literal";
  consumeString(stringObject);
}

void passStringLiteral(){
  consumeString("string literal");
}

Now consider the following two cases:

1) The function passStringObject() is called.

2) The function passStringLiteral() is called.

In case 1 I would assume that - when calling the function consumeString within passStringObject - the variable stringObject is just passed to the function consumeString and (because of call-by-value) the copy constructor of the string class is called so that the parameter str is a copy of the variable stringObject which was passed to the function consumeString.

But what happens in case 2 when the function consumeString is called? Is the (overloaded) assignment operator of the string class (maybe assigning the literal to some "hidden" variable in the background?) implicitly called before calling the copy constructor and copying the value of the "hidden" variable to the parameter str?


Solution

  • In case 2 the std::string(const char*) constructor will be called before the object is passed to consumeString, which will then copy the temporary string object.