Does this make a copy on a return or does the compiler do some magic? What is the magic, shared stack space?
string getCamel()
{
string s = "Camel";
return s;
}
main()
{
string myStr = getCamel();
}
Does this make a copy on a return or does the compiler do some magic? What is the magic, shared stack space?
string getCamel()
{
string s = "Camel";
return s;
}
main()
{
string myStr = getCamel();
}
The compiler can do the "magic" of just constructing the string directly in the variable being assigned to upon return. This is called "copy elision" and "return value optimization". It is allowed to do that, although not required to (until C++17 where it is required in some cases).
With C++11 and later the compiler also has the option of "moving" the variable into the destination if the type has a move constructer - less costly than a copy but still more costly than just eliding the operation and constructing directly in the destination.
See these references for more detail:
http://en.cppreference.com/w/cpp/language/copy_elision