c++ - 具有默认保护析构函数的类不是平凡可破坏的,但派生类是?

标签 c++ c++11 language-lawyer destructor

在下面的例子中,第一个静态断言被触发但第二个没有:

#include<type_traits>
struct A{
 protected:
  ~A()=default;
};
struct B:A{
  //this static assertion fails
  static_assert(std::is_trivially_destructible<A>::value,"");
};
//this static assertion succeeds
static_assert(std::is_trivially_destructible<B>::value,"");

(使用 GCC、Clang、MSVC、ellcc 检查)

我不明白为什么 A 在 B 内部不能是平凡可破坏的,而 B 是平凡可破坏的。这似乎与 C++ 标准的这两段矛盾,其中没有提到可访问性:

[class.dtor]

A destructor is trivial if it is not user-provided and if:

(6.1) — the destructor is not virtual,

(6.2) — all of the direct base classes of its class have trivial destructors, and

(6.3) — for all of the non-static data members of its class that are of class type (or array thereof), each such class has a trivial destructor.

[dcl.fct.def.default]

A function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration.

最佳答案

简单地说,因为从外部的角度来看,A 根本不可破坏! 析构函数是 protected,所以如果你有一个A* ptr,调用delete ptr会编译失败。

关于c++ - 具有默认保护析构函数的类不是平凡可破坏的,但派生类是?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46484307/

相关文章:

C++:转换成员函数指针

c++ - 评估 if ( std::function<void()> == function )?

c++ - 模板 :Name resolution -->can any one tell an other example for this statement. ..请

c++ - 在可移动类的构造函数中初始化 std::thread

arrays - 数组可以有尾部填充吗?

c - 在 C 中,如何确保内存加载只执行一次?

c++ - 使用<filesystem>库C++中的recursive_directory_iterator时,运行时库错误abort()引发

c++ - 为什么 vector 不循环更新?

c++ - std::regex_match与字符éèà

c++ - 不可复制但可移动的容器