std::vector::clear, constant time? [duplicate

2019-02-22 02:24发布

问题:

Possible Duplicate:
What is the complexity of std::vector<T>::clear() when T is a primitive type?

If I have a std::vector with a primitive type, and I call clear() (this way push_back starts at the beginning of the capacity), is the clear() call going to be completed in constant time or linear time? The documentation says it destroys all the elements, but if the element is an int, there shouldn't be anything to destroy, right?


edit: I found a duplicate that has a poster who explains in detail that the implementation can check whether the destructor is trivial, and gives an example of one compiler that has that check (GCC).

What is the complexity of std::vector<T>::clear() when T is a primitive type?

回答1:

It depends on how the vector is implemented, but an array of objects with trivial destructors (which includes PODs like built-in integral types such as int) should be able to be deallocated safely with a single call to vector<T>::allocator_type::deallocate without looping over the elements and individually invoking destructors. An implementation of std::vector can use type_traits or compiler internals to determine if T has a trivial destructor, and deallocate the internal array accordingly. You'll need to check the source code of your implementation to find out what it does, but most mainstream implementations of std::vector will give you constant-time deallocation for types with trivial destructors (or at least constant time for integral types and other PODs).



回答2:

The standard makes no guarantees about the complexity of std::vector::clear, though you'd expect the operation to be linear in the container's size for complex element types, and constant for PODs.