Captain Jack sparrow
Captain Jack sparrow

Reputation: 1029

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?

Upvotes: 1

Views: 117

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155734

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.

Upvotes: 5

Donghui Zhang
Donghui Zhang

Reputation: 1143

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

Upvotes: 3

Related Questions