Reputation: 1029
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?
Upvotes: 1
Views: 117
Reputation: 155734
You're overcomplicating. vector
s 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 vector
s automatically), this just introduces additional indirection and allocator overhead.
Upvotes: 5
Reputation: 1143
No need to use unique_ptr here. std::vector will free memory when the object goes out of scope.
Upvotes: 3