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?
 
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
 
ste5anSenior DeveloperCommented:
Cause it's not ensured that you as consumer of A::myfunction will free B.
0
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.