By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,379 Members | 3,035 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,379 IT Pros & Developers. It's quick & easy.

std::vector of objects

P: 16
here is something I am never quite sure about:

Expand|Select|Wrap|Line Numbers
  1. #include <vector>
  3. class MyClass{ .... };
  5. std::vector<MyClass*> v1;
  6. std::vector<MyClass> v2;
  8. v1.push_back(new MyClass(args));
  9. v2.push_back(MyClass(args));
  11. v1.pop_back();  // Memory leak, since not deleted?
  12. v2.pop_back();  // What here?
Thanks for any inputs :)

Nov 25 '10 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 5K+
P: 8,916
At line 12 everything is fine, std::vector and all stl containers have an allocator class that constructs and deletes contained objects as required so when v2.pop_back() is called there is no leak the memory is still under the control of the vector.

The problem with v1 is that the vector is not controlling you memory you allocated when you called new. Since you called new it is your responsibility to call delete but when you pop the value from the vector you loose the only reference to the new'd memory and so can't delete it, hence the leak.
Nov 26 '10 #2

P: 16
Nov 26 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.