user2203807
user2203807

Reputation: 63

Can you return a local variable of string object in C++?

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
   }

Upvotes: 2

Views: 104

Answers (2)

Dietmar Kühl
Dietmar Kühl

Reputation: 153955

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).

Upvotes: 0

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 11502

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.

Upvotes: 5

Related Questions