当 std::is_trivial_v<T> 为真时 T 可以有析构函数吗?

Can T have a destructor when std::is_trivial_v<T> is true?

#include <type_traits>

struct A
{
    ~A() {}
};

int main()
{
    static_assert(std::is_trivial_v<A>); // error   
}

很明显,如果 A 有析构函数,std::is_trivial_v<A> 将是 false

但是,从std::is_trivialcppref page来看,没有什么要求A不能有析构函数。

可以 T std::is_trivial_v<T> 为真时有析构函数吗?

Can T has a destructor when std::is_trivial_v<T> is true?

它不能有非平凡的析构函数。如果以下所有条件都为真,则 class T 的析构函数是微不足道的:

  • The destructor is not user-provided (meaning, it is either implicitly declared, or explicitly defined as defaulted on its first declaration)
  • The destructor is not virtual (that is, the base class destructor is not virtual)
  • All direct base classes have trivial destructors
  • All non-static data members of class type (or array of class type) have trivial destructors

当一个类型是普通类型时,这意味着它暗示它可以被普通破坏。
像您那样显式定义方法将不符合此约束条件。
但你可以做的是:

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

static_assert(std::is_trivial<A>::value);

你需要在兔子洞里走得更远。 cppreference 页面说普通类型需要 TriviallyCopyable。如果您访问该页面,它需要

Trivial non-deleted destructor

如果我们访问那个link我们有

Trivial destructor

The destructor for class T is trivial if all of the following is true:

  • The destructor is not user-provided (meaning, it is either implicitly declared, or explicitly defined as defaulted on its first declaration)
  • The destructor is not virtual (that is, the base class destructor is not virtual)
  • All direct base classes have trivial destructors
  • All non-static data members of class type (or array of class type) have trivial destructors

A trivial destructor is a destructor that performs no action. Objects with trivial destructors don't require a delete-expression and may be disposed of by simply deallocating their storage. All data types compatible with the C language (POD types) are trivially destructible.

所以,是的,它需要一个普通的析构函数,而您的用户提供的空析构函数不被认为是普通的。

唯一可以“编写”析构函数并将其视为微不足道的方法是使用

~ClassName() = default;