gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:06:19 24 4
gpt4 key购买 nike

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

#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 suchclass has a trivial destructor.

[dcl.fct.def.default]

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

最佳答案

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com