Suppose there exists a type T
such that std::is_trivially_destructable<T>::value == true
, and suppose further that T
is the value type of some vector class. When the vector's destructor is called, or the vector is assigned to another vector, it must destroy and deallocate its current storage. As T
is trivially destructable, is it necessary that I call T
's destructor?
Thanks for your help!
No, you don't need to call the destructors explicitly. This will be done by the
vector
's destructor.According to the C++ Standard (section 3.8), you can end an object's lifetime by deallocating or reusing its storage. There's no need to call a destructor that does nothing. On the other hand, letting the compiler optimize away an empty destructor usually results in cleaner and simpler code. Only if you can save substantial additional work, such as iterating through the collection, would you want to special-case trivial destructors.
libstdc++ (the standard library the gcc uses by default) applies precisely this optimisation:
And the specialisation of
std::_Destroy_aux
for__has_trivial_destructor(_Value_type) == true
:I would expect that most other well-written standard library implementations do the same.