Consider the following example:
1. Does the takeAFoo() function create a memory leak? Or is the foo& it returns bound to the scope of "afoo" in main, and since afoo isn't a pointer in main, no memory is leaked?Code:#include <iostream> #include <stack> struct Foo{ Foo( int n ):num(n){} int num; }; class Bar{ public: Bar(){ for( int i = 0; i < 10; i++ ) stackOFoos.push( Foo(i) ); } const Foo& takeAFoo(){ Foo* afoo = &stackOFoos.top(); stackOFoos.pop(); return *afoo; } int howManyFoos(){ return stackOFoos.size(); } private: std::stack<Foo> stackOFoos; }; int main(){ Bar bar; std::cout << bar.howManyFoos() << "\n"; Foo afoo = bar.takeAFoo(); std::cout << bar.howManyFoos() << "\n"; return 0; }
2. Also, takeAFoo won't work if the function is declared const like this:
Why is that?Code:const Foo& takeAFoo() const{ Foo* afoo = &stackOFoos.top(); stackOFoos.pop(); return *afoo; }
3. As a design consideration, I do want to be able to take a foo out of the bar class and do whatever I want with it. Is there a better way to go about achieving that kind of behavior?



LinkBack URL
About LinkBacks


