问题描述
假设存在 T
,使得 std :: is_trivially_destructable< T> :: value == true
,并进一步假设 T
是一些向量类的值类型。当向量的析构函数被调用,或者向量被分配给另一个向量时,它必须销毁和释放它当前的存储。因为 T
是可简单破坏的,是否需要调用 T
的析构函数?
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?
感谢您的帮助!
推荐答案
根据C ++标准通过重新分配或重用其存储来结束对象的生命周期。没有必要调用没有什么作用的析构函数。另一方面,让编译器优化一个空的析构函数通常会导致更干净和更简单的代码。只有当你可以节省大量额外的工作,例如迭代集合,你想要特殊情况下的平凡析构函数。
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.
这篇关于调用析构函数的简单可破坏性和必要性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!