Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 279
  • Last Modified:

Returning an object from a function

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
tommym121
Asked:
tommym121
1 Solution
 
jkrCommented:
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
 
tommym121Author Commented:
Thanks.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now