4

I've searched around and not found anything - does C++ give any guarantee on the order that items in a std::vector will be deleted when calling vector::clear()?

I have a vector with some items which depend on other items in the vector, so need to ensure it is cleared LIFO. FIFO would be fine - I can reverse the vector before calling clear().

Brad
  • 5,492
  • 23
  • 34
  • 1
    Do the *destructors* depend on the linked elements? If not, then the order of destruction would not matter. – eerorika Jan 09 '19 at 20:22
  • 2
    The [requirements for a sequence container](https://timsong-cpp.github.io/cppwp/sequence.reqmts#tab:containers.sequence.requirements) just say `clear()` destroys all elements, the container's `empty()` returns `true` and the complexity is linear. The section on `std::vector` doesn't add anything to that so it seems the order is unspecified. – François Andrieux Jan 09 '19 at 20:22
  • @errorika, sorry I should have been more clear - yes the destructors (in some cases) depend on other elements in the container. – Brad Jan 09 '19 at 20:25
  • Vectors are not LIFO/FIFO containers, they don't have a record of insertion order. –  Jan 09 '19 at 20:25
  • Use a container that preserve the insertion order, like std::stack – Amadeus Jan 09 '19 at 20:25
  • @Brad How are the elements linked to each other? A bare pointer? Something else? – eerorika Jan 09 '19 at 20:26
  • @Amadeus `std::stack` doesn't even have a `clear` operation. And doesn't give any further guarantees about destruction order of elements upon destruction of the stack. – eerorika Jan 09 '19 at 20:31
  • @eerorika -- but `std::stack` **does** keep track of insertion order; `while (!empty) pop()` will clear the stack with destruction in LIFO order. – Pete Becker Jan 09 '19 at 20:34
  • @PeteBecker You can achieve the same without the `stack` wrapper too using `pop_back`. Brad doesn't describe what other operations they need, but I suppose if no other operations are needed `stack` could be a good choice. – eerorika Jan 09 '19 at 20:37
  • Do your dependent objects continue to function if they are *copied*, *moved* or *swapped*? – Galik Jan 09 '19 at 20:49

1 Answers1

4

According to the sequence container requirements(std::vector is one of those) the standard only says this about clear():

Destroys all elements in a. Invalidates all references, pointers, and iterators referring to the elements of a and may invalidate the past-the-end iterator.

Ensures: a.empty() returns true.

Complexity: Linear.

So no, you get no guarantees on the order of destruction.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122