1

I am using a vector of vectors in a c++ function.

    vector<vector<int>> foo

I want to free memory automatically when this object goes out of scope. In order to do this I am using the following instead:

    unique_ptr<vector<unique_ptr<vector<int>>> foo(new vector<unique_ptr<vector<int>>())

Does this sound right or I am unnecessarily complicating?

PS: If not using unique_ptr I would like to allocate vectors on the heap. That is

    vector<vector<int>>* foo = new vector<vector<int>>();

So I think I would have to manually cleanup things when foo is supposed to go out of scope?

Captain Jack sparrow
  • 959
  • 1
  • 13
  • 28

2 Answers2

5

You're overcomplicating. vectors are already self-cleaning (the destructor will be called for the top-level vector when it goes out of scope, which calls it for each of the contained vectors automatically), this just introduces additional indirection and allocator overhead.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • I am allocating the vector foo on the heap. Does it not require having to delete them manually? – Captain Jack sparrow Oct 13 '16 at 22:24
  • @CaptainJacksparrow There is no need to allocate a vector on the heap because the vector already allocates all its internal data on the heap. A vector is basically a smart pointer to an array with deep copy semantics. – Galik Oct 13 '16 at 22:27
  • @Galik I am a c++ noob :) . Any resource on the internet that you can guide me for more info? – Captain Jack sparrow Oct 13 '16 at 22:29
  • @CaptainJacksparrow It is well worth getting a good book as there is a lot of hit and miss on the web: These are good recommendations https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Galik Oct 13 '16 at 22:33
  • Does this (allocation on the heap, destructor called for members on out of scope) hold true for other datastructures like unordered_maps ? – Captain Jack sparrow Oct 13 '16 at 22:37
  • @CaptainJacksparrow: Yup. If you, for some reason, need the `vector` data itself on the heap (the internal array of values is always on the heap, so the `vector` "data" is basically a pointer to that internal array, plus a current size and allocated capacity, maybe a few other scalar values depending on implementation), you could allocate the outer `vector` on the heap and use a `unique_ptr` to store it, but usually there's no need. In C++11, with the named return value optimization, a stack allocated `vector` returned by a function will be constructed directly into caller space, no copying. – ShadowRanger Oct 13 '16 at 22:42
3

No need to use unique_ptr here. std::vector will free memory when the object goes out of scope.

Donghui Zhang
  • 1,133
  • 6
  • 8