2

I found the following piece of code somewhere and I was wondering if it is legal or not in C++. ret variable is stack variable, and once foo returns the memory allocated to ret no longer exists. But string is a class, and I think copy constructor is called to copy the contents of ret to var. Is this true? is the following piece of code valid?

    string foo(int x)
    {
        string ret; 
        //some operation on ret

        return ret; 
    }
    string callingFunc()
   {
        string var = foo(2); 
        // some operation on var
   }

2 Answers2

5

Yes it is

Actually 3 objects are constructed: ret due to string ret;, a temporary due to return ret;, and var constructed from the mentioned returned temporary.

The compiler might optimize away the temporary constructing var from ret directly.

Sebastian Hoffmann
  • 11,127
  • 7
  • 49
  • 77
  • Thanks for your answer. The only thing that I don't understand is how come when I provide explicit copy and assignment constructors which print out, nothing is actually being printed out on the screen? – user2203807 Dec 30 '13 at 00:52
  • @user2203807 try it with an older compiler. With c++11 move constructors were introduced allowing you to just move around ressources (/changing the ownership) and not making a deep copy. Basically just the pointers of two string instances are swapped, see http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom (which also explains move constructors to some degree, for a more indepth explanation see http://stackoverflow.com/questions/3106110/what-is-move-semantics) – Sebastian Hoffmann Dec 30 '13 at 11:48
0

The code is not legal as is: callingFunc() is declared to return a std::string but isn't returning anything. If this function is called and not exited with an exception you'll get undefined behavior.

The function foo() is correct, however: you can return local variables by value. Conceptually they will be copied (or moved which is a constructor similar to the copy constructor but indicating that the object copied from will go away and it is OK to change its content as a result) in the return-statement before the function exists. The compiler is, however, allowed to elide the copy when the variable is returned directly (basically, the object is directly constructed in the location where there returned value is expected making the copy unnecessary).

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380