Solved

Returning an object from a function

Posted on 2014-01-23
2
260 Views
Last Modified: 2014-01-23
I am a bit confuse with object return in general. Am I right the copy constructor being called for the object when a function return the object.

For example,

std::string ReturnStringFunction (std::string str)
{
    std::string s = str;
    return s;
}

Now in the main program

main()
{
       std::string s1;
       std::string s2;
       s1 = ReturnStringFunction ("DummyString1");
       s1 = ReturnStringFunction ("Dummy2");
       // ??? am I protentially introduce a memory leak here?

       s2 = ReturnStringFunction ("Dummy2");
       // ??? am I introduce a different copy of "Dummy2", 2 different memory location.


}
0
Comment
Question by:tommym121
2 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 500 total points
ID: 39805087
No, no memory leaks will occur in the above. The assignment operator for a 'std::string' will dispose and clean up any allocated memory before storing the new contents. 's' will be cleaned up when 'ReturnStringFunction()' exits.
And yes, "Dummy2" will be stored in two string objects, both of which will allocate the memory on the process' heap.
0
 

Author Closing Comment

by:tommym121
ID: 39805167
Thanks.
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

785 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question