mercredi 28 septembre 2016

Initializing a std::string with function return value, is there a copy?

I have the following code, I am using GCC and C++11:

std::string system_call(const char *cmd){
   std::string a;
   ...
   return a;
}

std::string st = system_call("whatever code");

Is there an implicit copy there? I am calling this function many times, and I guess it is doing a copy from the return value of the system_call to the variable st, and later on releasing the temporary r-value.

Is there any way I can avoid the copy? Using st.swap(system_call()) throws and error in the compiler:

error: no matching function for call to 'std::basic_string::swap(std::string)'

My questions are:

  1. If there is a problem or not
  2. How to avoid it, if there is one

Thanks

Aucun commentaire:

Enregistrer un commentaire