0

Learning smart pointers and stumble upon this problem: How would I create a vector with objects that auto deletes themselves? Below is a snippet of how I have it at the moment, is this the correct way to ensure I don't need to call delete on anything?

unique_ptr<vector<unique_ptr<OBJ>>> list(new vector<unique_ptr<OBJ>>);
David S
  • 195
  • 5
  • 19
  • 1
    You can't use `auto_ptr`, but `unique_ptr` is fine if your compiler provides it. You need move semantics to get the correct behavior. – Cody Gray - on strike Feb 13 '16 at 13:10
  • @CodeGray No complains from the compiler so I take it it's working then, why wouldn't auto_ptr work? – David S Feb 13 '16 at 13:12
  • 1
    `auto_ptr` has rather unusual semantics, such that copying it actually transfers ownership rather than making a copy. Related reading: http://stackoverflow.com/questions/4577838/smart-pointers-in-container-like-stdvector, http://stackoverflow.com/questions/2876641/so-can-unique-ptr-be-used-safely-in-stl-collections – Cody Gray - on strike Feb 13 '16 at 13:14
  • 3
    That first unique_ptr is probably redundant. vector> list; is probably enough. This is not Java where you have to 'new' absolutely everything... – H. Guijt Feb 13 '16 at 13:18
  • 1
    If you put objects to a vector then they will be destroyed when the vector is, not clear why use smart pointer here – user3528438 Feb 13 '16 at 13:21

1 Answers1

1

H.Guijt pointed out the redundancy on calling new on the vector itself, following code should be sufficient:

vector<unique_ptr<Entry>> list;
David S
  • 195
  • 5
  • 19