Captain Jack sparrow Captain Jack sparrow - 1 year ago 69
C++ Question

how to use unique_ptr to automatically manage memory for vector<vector<int>>

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download