return type

HI

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

Eg

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

thanks
LuckyLucksAsked:
Who is Participating?

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

x
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.
0
jkrCommented:
That will depend on how 'A::myfunction()' instatiates 'B', consider

class A {

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

protected:
B b;
};

Open in new window

vs.
class A {

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

protected:
B* b;
};

Open in new window


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

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
sarabandeCommented:
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.

Sara
0
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
C++

From novice to tech pro — start learning today.