Search code examples
c++memoryc++11destructortype-traits

Trivial Destructibility and Necessity of Calling Destructor


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!


Solution

  • 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.