简体   繁体   中英

deleting c-style array of int vectors

I have declared:

vector<int> * part = new vector<int>[indmap];

Ok, I know it: “why don't you declare a vector of vector?”. The next time I will do so, but now I would like to understand something more about vectors which I'm not able to solve.

Now I want to release all resources, what have I to do?

delete[] part;  

But before deleting the array what should I do to delete all the vector objects?

No, you don't. There's just one simple rule (when you do not use smart pointers ) - use delete when you have used new .

So, there's just one new[] here, you need just one delete[] .

@Joachim Pileborg is right, but then you'll have more new -s, so, you'll need more delete -s.

It depends on the contents of the vector. If it contains raw pointer (like int * ) you need to iterate the vector and delete all entries manually. Otherwise, if it contains just basic types, or objects (not pointers to them) or smart pointers it will be handled automatically.

When you use delete , the destructor of the pointed-to object is called before de-allocation (do this, when you have created an object using new ).

Similarly, the destructors of all created objects are called when you use the array version delete[] (do this, when you have allocated an array of objects using new[] ).

The destructor of a std::vector<T> automatically calls the destructors of the contained objects.

So, as Joachim Pileborg has pointed out in his answer, you need to take care of deleting the vector's objects manually, only when you have raw pointers in there that point to dynamically allocated objects (eg, objects allocated by new ) and you are responsible for their deletion (ie, you own them). Raw pointers don't have destructors that would destroy the pointed-to objects, so you would have to iterate the vector to delete the objects manually in this case. Otherwise the vector can simply be destroyed (or array-deleted, in this case).

As a rule of thumb:

  • You need to delete memory you have allocated using new .
  • You need to delete[] memory you have allocated using new[] .
  • You can pass this obligation to smart pointers, ie, objects that implement an ownership policy that will take care of the proper deallocation.
  • You should avoid dynamic memory allocation where ever possible and prefer schemes like RAII for memory management.

For reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM