return type


Why would a function returning B& cause a memory leak? B,A are two C++ classes.


B& A::myfunction(){ ....}

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ste5anSenior DeveloperCommented:
Cause it's not ensured that you as consumer of A::myfunction will free B.
That will depend on how 'A::myfunction()' instatiates 'B', consider

class A {

B& myfunction() { return b;} // no memory leak

B b;

Open in new window

class A {

B& myfunction() { b = new B; return *b;} // leaves a memory leak

B* b;

Open in new window

so it si diffcult to answer 'yes' or 'no' without knowing the big bicture.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Why would a function returning B& cause a memory leak?
returning a reference to any type would never cause a memory leak. moreover, when using a reference rather than  a value, it is guaranteed that the return operation itself doesn't allocate new memory (beside of the unlikely case that there is a customized cast operator involved). so, if a leak was detected after return it was caused because the called function didn't free all of its resources it has allocated when called. that can be due to an explicit allocation (see sample of jkr) or implicitly because local (class) objects were freed (by their destructor) but didn't free all their allocations correctly. for example if the function has used a container of pointers to objects - each of them allocated with new operator - but the function didn't delete these elements explicitly by iterating the container before return, you would encounter leaks after call because of that.

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.