Solved

Returning an object from a function

Posted on 2014-01-23
2
265 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
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 learn how to clear a vector as well as how to detect empty vectors in C++.

751 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