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

I have the following code, I use 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 call this function many times, and I assume that it executes a copy from the return value system_callto the variable st, and then frees the temporary value of r.

Is there any way to avoid copying? Using st.swap(system_call())throws and errors in the compiler:

error: there is no corresponding function to call 'Stand :: basic_string :: swap (std :: string)

My questions:

  • If there is a problem or not
  • How to avoid this, if any

thank

EDIT: . , , , st - .

system_call("whatever").swap(st);
+4
3

, std::string, ( copy elision), , - RVO ( @NathanOliver ), . ++ 17 .

, , , ++ 11 , std::string . std::move , RVO. , RVO , , , .

+13

Elision - , , , .

std::string system_call(const char *cmd){
  std::string a;
  ...
  return a; // all return paths return `a` directly
}

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

elision , a, system_call st - .

elide, , " elide", . ", , ", , , .

, .

elision ( ), ++ 11. std::string , ; .

Elision , , - . , .

Elision , return return named_variable; return some_temporary_object;, . , some_type bob = some_temporary;, some_temporary - some_type. ( ).

"" .

++ 17 .

elision ++ 14 , . , , . ++ 17, "" , : , , " ", .

+4

c++11, , c++11.

, system_call, . st . .

+3

Source: https://habr.com/ru/post/1656102/


All Articles