std::vector of objects

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sandromani
    New Member
    • Dec 2007
    • 16

    #1

    std::vector of objects

    Hi,
    here is something I am never quite sure about:

    Code:
    #include <vector>
    
    class MyClass{ .... };
    
    std::vector<MyClass*> v1;
    std::vector<MyClass> v2;
    
    v1.push_back(new MyClass(args));
    v2.push_back(MyClass(args));
    
    v1.pop_back();  // Memory leak, since not deleted?
    v2.pop_back();  // What here?
    Thanks for any inputs :)

    sandro
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    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.

    Comment

    • sandromani
      New Member
      • Dec 2007
      • 16

      #3
      Thanks!
      sandro

      Comment

      Working...