Question

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?

Was it helpful?

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.

OTHER TIPS

String literals spawn temporary std::string objects.

The lifetime of the temporary object is bound to the C++ instruction which created it.

In the case std::string stringObject = "string literal"; a constructor from const char* is invoked to create an object (which is not temporary).

In the case of the string literal, a temporary std::string object is created, and then copied to the parameter.

In case 1 the you are the person who is creating the object, and when the function is called the copy constructor of the string class is called and the string is copied.

In the second case the, parametrized constructor (with char * parameter) is called to construct the string object.

in case 2 the destructor string class will be called as soon as the consumeString returns, and in first case the destructor will be called twice once for the temperory variable in the consumeString function and other for variable in passStringObject;

In the case1 the string object is created in the local memory heap and we pass the object to the calling.

In the case2 the string object is created in the stack and that object is passed to the calling function, on return it get deleted automatically

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top