std::is_trivially_destructible

本文详细介绍了如何使用C++标准库中的std::is_trivially_destructible来判断一个类型是否为容易销毁的类型。文章通过具体实例说明了该特性,并解释了在SystemC中的sc_bv类型为何不被认为是trivially destructible。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

std::is_trivially_destructible来判断 一个 内置类型或structure/class/union类型 是否为 “容易销毁的(trivially destructible)”,从字面意思也可以看出,主要是check这个类型的 析构函数。官网给出如下解释:

A trivially destructible class is a class (defined with class, struct or union) that:

  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.

也就是说,如果一个类定义了非默认的析构函数,比如类的构造函数中有new,那么需要自写析构来delete,那么std::is_trivially_destructible<T>::value将返回false。

如果一个类中的 非静态成员变量 是 not rivially destructible types,那么 这个类 也将是not rivially destructible types,std::is_trivially_destructible<T>::value将返回false。

在SystemC中,对于sc_bv 类型,由于其基类sc_bv_base有自定义析构函数,所以std::is_trivially_destructible<sc_dt::sc_bv<2>>::value 返回false。

    virtual ~sc_bv_base()
    { delete [] m_data; }

参考:

is_trivially_destructible - C++ Reference

C++ std::is_trivially_destructible用法及代码示例 - 纯净天空

STL in C++11 (Allocator 2) - 简书

// execute:
//     g++ -g -Wall -lsystemc -m64 -pthread main.cpp
//         -L/$(your systemc path)/lib-linux64
//         -I/$(your systemc path)/include  -I/$(your systemc path)/src/tlm_utils -o sim

#include <systemc>

// C++ program to illustrate
// std::is_trivially_destructible
#include <bits/stdc++.h>
#include <type_traits>
using namespace std;

struct Y
{
  Y(int, int){};
};

struct X
{
  // Destructor
  ~X() noexcept(false)
  {
  }
};

struct Z
{
  ~Z() = default;
};

class A
{
  virtual void fn() {}
};

class MyBvClass
{
  sc_dt::sc_bv<2> m_test_mem;
};

int sc_main(int argc, char **argv)
{
  cout << boolalpha;
  cout << "int:"
       << std::is_trivially_destructible<int>::value
       << endl;
  cout << "struct X:"
       << std::is_trivially_destructible<X>::value
       << endl;
  cout << "struct Y:"
       << std::is_trivially_destructible<Y>::value
       << endl;
  cout << "struct Z:"
       << std::is_trivially_destructible<Z>::value
       << endl;
  cout << "class A:"
       << std::is_trivially_destructible<A>::value
       << endl;
  cout << "class MyBvClass:"
       << std::is_trivially_destructible<MyBvClass>::value
       << endl;

  sc_core::sc_start();
  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

123axj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值