0

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();
}
user846566
  • 373
  • 1
  • 3
  • 12
  • 1
    It is allowed to ellide the copy, not required. – Hatted Rooster Aug 18 '16 at 18:51
  • [This](http://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization) look like what you are looking for – NathanOliver Aug 18 '16 at 18:51
  • Since C++11, there can be no copy, only optional move constructors. – aschepler Aug 18 '16 at 18:55
  • @aschepler No. Only since C++17 is copy elision guaranteed (in some cases). It is still completely valid for a C++11 compiler to do a copy (even if it *could* elide the copy or do a move) - but modern compilers try hard to elide or move. – Jesper Juhl Aug 18 '16 at 19:00
  • @JesperJuhl No, when you `return` an identifier that names a local variable, the compiler must search for a move constructor before a copy constructor. C++14 12.8/32. – aschepler Aug 18 '16 at 19:07
  • If the type is not movable it can do a copy. But you said "there can be no copy" which is not true. You are right that it must prefer move over copy though. – Jesper Juhl Aug 18 '16 at 19:10

1 Answers1

1

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

https://en.m.wikipedia.org/wiki/Return_value_optimization

http://en.cppreference.com/w/cpp/language/move_constructor

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70