Solved

Returning an object from a function

Posted on 2014-01-23
2
255 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
Comment Utility
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
Comment Utility
Thanks.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

772 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now