Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the pop_back() of std::list de-allocate memory?

Tags:

c++

c++11

I've created a list of stacks.

using namespace std;
list<stack<int>*> stacks;
stack<int> *st = new stack<int>();      //LINE0
stacks.push_back(st);
st->push(10);   
stack<int> *last = stacks.back();
stacks.pop_back();    //LINE1
delete last;          //LINE2

Does LINE1 de-allocate memory allocated at LINE0 automatically? Do I need LINE2?

like image 992
John Avatar asked Dec 18 '25 04:12

John


1 Answers

You allocated memory for the stack using new, so yes, you'll need to delete it manually. To make life easier, use a list<stack<int>> instead, it's unlikely you need a list of pointers.

list<stack<int>> stacks;
stack<int> st = stack<int>();
stacks.push_back(st);
stacks.back().push(10);   
stack<int> last = stacks.back();
stacks.pop_back();

No need to bother with managing memory anymore. If you really need a list of pointers, use a smart pointer instead of raw pointers.

list<unique_ptr<stack<int>>> stacks;
auto st = unique_ptr(new stack<int>());
stacks.push_back(std::move(st));
stacks.back()->push(10);   
auto last = std::move(stacks.back());
stacks.pop_back();

Again, you don't need to worry about manually freeing memory. With C++14, you can also get rid of the new.

auto st = make_unique<int>();
like image 173
Praetorian Avatar answered Dec 20 '25 19:12

Praetorian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!