Trivial destructibility and the need to call the destructor

Suppose there exists a type Tsuch that std::is_trivially_destructable<T>::value == true, and further assume that Tis the value type of some vector class. When a vector destructor is called or a vector is assigned to another vector, it must destroy and release its current storage. Since it is Ttrivially destructible, is it necessary for me to call the Tdestructor?

Thank you for your help!

+5
source share
3 answers

According to the C ++ standard (section 3.8), you can end the lifetime of an object by freeing or reusing its storage. There is no need to call a destructor that does nothing. On the other hand, letting the compiler optimize an empty destructor usually produces cleaner and simpler code. Only if you can save significant additional work, such as iterating through a collection, would you like to use trivial special case destructors.

+8
source

libstdC ++ (the standard library used by gcc by default) uses this particular optimization :

  117   /**
  118    * Destroy a range of objects.  If the value_type of the object has
  119    * a trivial destructor, the compiler should optimize all of this
  120    * away, otherwise the objects' destructors must be invoked.
  121    */
  122   template<typename _ForwardIterator>
  123     inline void
  124     _Destroy(_ForwardIterator __first, _ForwardIterator __last)
  125     {
  126       typedef typename iterator_traits<_ForwardIterator>::value_type
  127                        _Value_type;
  128       std::_Destroy_aux<__has_trivial_destructor(_Value_type)>::
  129     __destroy(__first, __last);
  130     }

And specialization std::_Destroy_auxfor __has_trivial_destructor(_Value_type) == true:

  109   template<>
  110     struct _Destroy_aux<true>
  111     {
  112       template<typename _ForwardIterator>
  113         static void
  114         __destroy(_ForwardIterator, _ForwardIterator) { }
  115     };

I would expect most other well-written standard library implementations to do the same.

+5

, . vector.

+1

All Articles