在下面的例子中,第一个静态断言被触发但第二个没有:
#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/