gpt4 book ai didi

c++ - 当基类成员的析构函数具有非空 noexcept 说明符和主体时,析构函数上的 C2694

转载 作者:IT老高 更新时间:2023-10-28 22:15:08 25 4
gpt4 key购买 nike

我遇到了无法解释的编译器错误,也无法在网上找到相关信息。我最近在包装器类的析构函数中添加了一个 noexcept 说明符,现在大量从使用此包装器的类继承的类无法编译。我已经用 GCC 4.9 试过了,没有编译器错误。

我正在使用 Visual Studio Professional 2015 版本 14.0.25431.01 更新 3

考虑以下重现问题的最小代码:

#include <type_traits>

template<class T>
struct member
{
~member() noexcept(std::is_nothrow_destructible<T>::value) {};
};

struct parent
{
virtual ~parent() noexcept = default;
};


struct derived : public parent
{
member<int> x;
};

该片段产生以下错误消息:

1>c:\users\fandrieux\workspace\tmp\dtor_noexcept\main.cpp(19): error C2694: 'derived::~derived(void) noexcept(<expr>)': overriding virtual function has less restrictive exception specification than base class virtual member function 'parent::~parent(void) noexcept'
1> c:\users\fandrieux\workspace\tmp\dtor_noexcept\main.cpp(19): note: compiler has generated 'derived::~derived' here
1> c:\users\fandrieux\workspace\tmp\dtor_noexcept\main.cpp(12): note: see declaration of 'parent::~parent'

我觉得有趣的是,如果您将成员的析构函数体替换为 = default 或使用 noexceptnoexcept(true):

// None of these produce compiler errors
virtual ~member() noexcept(std::is_nothrow_destructible<T>::value) = default;
virtual ~member() noexcept(true) {}
virtual ~member() noexcept {}

我知道它的析构函数不会抛出。偏执狂和怀疑论者(像我一样)可以添加以下静态断言并自行检查:

static_assert(std::is_nothrow_destructible<T>::value, "Might throw!");

According to MSDN它表示动态异常说明符不足。这在这里如何应用? noexcept([boolean expression]) 不等同于 noexcept(true)noexcept(false) 吗?为什么这会根据函数体的存在而改变?向派生添加显式 noexcept 析构函数可以避免编译器错误,但这感觉像是一种不必要的解决方法。实际上,当您考虑到每个派生类都必须更新时,这也是一个相当大的负担。

最佳答案

这看起来像一个编译器错误。如果我们添加以下类:

struct dtor_throws
{
~dtor_throws() noexcept(false) {}
};

并因此改变derived的定义:

struct derived : public parent
{
member<dtor_throws> x;
};

然后GCC和Clang都提示~derived的异常规范比~parent宽松。

在原始示例中,MSVC 似乎没有将 noexcept 表达式的 value 嵌入到 ~parent 类型中,而只是将用户定义的类模板析构函数的所有复合 noexcept 规范视为比 noexcept(true) 更宽松。

MSVC 2017 RC 也受到影响。

关于c++ - 当基类成员的析构函数具有非空 noexcept 说明符和主体时,析构函数上的 C2694,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41402348/

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