Consider the following example:
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;
}
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?
2. Also, takeAFoo won't work if the function is declared const like this:
Code:
const Foo& takeAFoo() const{
Foo* afoo = &stackOFoos.top();
stackOFoos.pop();
return *afoo;
}
Why is that?
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?