trivivally destructible类(class、struct 或者 union),需要满足下面条件:
1. uses the implicitly defined destructor.
2. the destructor is not virtual.
3. its base class and non - static data members(if any) are themselves also trivially destructible types.
而对应的std::is_trivially_destructible函数用来判断当前类型是否为trivivally destructible,实例代码如下:
#include <iostream>
#include <type_traits>
using namespace std;
// 声明一个结构体
struct Y {
// 构造函数
Y(int, int) {};
};
struct X {
// 析构函数
// noexcept 表示其修饰的函数不会抛出异常。不过与throw()动态异常声明不同,
// 对于C++11,如果noexcept修饰的函数抛出了异常,编译器可以选择直接调用
// std::terminate()函数来终止程序的运行,这比基于异常机制的throw()在
// 效率上会高一些。这是因为异常机制会带来一些额外开销,比如函数抛出异常,
// 会导致函数栈被依次地展开(unwind),并依帧调用在本帧中已构造的自动变量的析构函数等,
// 两种调用方法:
// 1.noexcept后面不接常量表达式:简单地表明函数不会抛出异常。
// 2.noexcept后面接常量表达式: 常量表达式的结果会被转换成一个bool类型的值。该值为true,
// 表示函数不会抛出异常,反之,则有可能抛出异常。不带常量表达式的noexcept相当于声明了noexcept(true),
// 即不会抛出异常。在通常情况下,在C++11中使用noexcept可以有效地阻止异常的传播与扩散。
~X() noexcept(false)
{
}
};
struct Z {
~Z() = default;
};
// 声明一个类
class A {
virtual void fn() {}
};
class B {
virtual ~B();
};
// 派生类代码
int main()
{
// 调用boolalpha函数后,再次打印bool类型时,
// 将以string的形式打印"true"或者"false"。
cout << boolalpha;
// 检测int是否为 trivially
// 可销毁或者不能
cout << "int:"
<< is_trivially_destructible<int>::value
<< endl;
// 检测结构体X是否为trivially
// 可销毁或者不能
cout << "struct X:"
<< is_trivially_destructible<X>::value
<< endl;
// 检测结构体Y是否为trivially
// 可销毁或者不能
cout << "struct Y:"
<< is_trivially_destructible<Y>::value
<< endl;
// 检测结构体Z是否为trivially
// 可销毁或者不能
cout << "struct Z:"
<< is_trivially_destructible<Z>::value
<< endl;
// 检测类A是否为trivially
// 可销毁或者不能
cout << "class A:"
<< is_trivially_destructible<A>::value
<< endl;
// 检测类B是否为trivially
// 可销毁或者不能
cout << "class B:"
<< is_trivially_destructible<B>::value
<< endl;
// 检测结构体Y(int,int)是否为trivially
// 可销毁或者不能
cout << "Constructor Y(int, int):"
<< is_trivially_destructible<Y(int, int)>::value
<< endl;
return 0;
}
输出结果如下:
int:true
struct X:false
struct Y:true
struct Z:true
class A:true
class B:false
Constructor Y(int, int):false
来具体分析下,struct X违反了条件1,析构函数并不是隐式调用;class B违反了条件2,析构函数为虚函数;Constructor Y(int, int)违反了条件3,非静态成员不是trivivally destructible。