覆盖[[noreturn]]虚拟函数 [英] Overriding a [[noreturn]] virtual function

查看:75
本文介绍了覆盖[[noreturn]]虚拟函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[[noreturn]] 属性可以应用于不打算返回的函数。例如:

The [[noreturn]] attribute can be applied to functions that are not meant to return. For example:

[[noreturn]] void will_throw() { throw std::runtime_error("bad, bad, bad ...."); }

但是我遇到了以下情况(不,我没有设计):

But I've encountered the following situation (no, I didn't design this):

class B {
public:
  virtual void f() { throw std::runtime_error(""); }
};

class D : public B {
  void f() override { std::cout << "Hi" << std::endl; }
};

我真的想放置属性 [[noreturn]] B :: f()声明上的code>。但是我不清楚派生类中的覆盖会发生什么。从 [[noreturn]] 函数成功返回会导致未定义的行为,我当然不希望如果重写也继承了该属性。

I would really like to place the attribute [[noreturn]] on the B::f() declaration. But I'm unclear as to what happens to the override in the derived class. Successfully returning from a [[noreturn]] function results in undefined behavior, and I certainly don't want that if an override also inherits the attribute.

问题::通过覆盖 [[noreturn]虚拟void B :: f(),我可以继承吗? [[noreturn]] 属性?

The question: By overriding [[noreturn] virtual void B::f(), do I inherit the [[noreturn]] attribute?

我浏览了C ++ 14标准,

I've looked through the C++14 standard, and I'm having trouble determining if attributes are inherited.

推荐答案

在实践中, g ++ c语 MSVC 认为 [[noreturn]] 属性是继承的

In practice, neither g++, clang nor MSVC consider the [[noreturn]] attribute as inherited

#include <iostream>

struct B {
public:
  [[noreturn]] virtual void f() { std::cout << "B\n"; throw 0; }
};

struct D : public B {
  void f() override { std::cout << "D\n"; }
};

int main() 
{
    try { B{}.f(); } catch(...) {}
    D{}.f();

    B* d = new D{};
    d->f();
}

会全部打印出 B, D和 D三个编译器。

which prints out "B", "D" and "D" for all three compilers.

这篇关于覆盖[[noreturn]]虚拟函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆