Overriding a [[noreturn]] virtual function

后端 未结 3 1895
小蘑菇
小蘑菇 2021-01-07 19:26

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

[[noreturn]] void will_throw() { throw std::r         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-07 20:14

    Consider what you are actually saying:

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

    Certainly the human reader, and possibly the compiler, would interpret this as a 'contract', i.e.
    "f() wont return, I promise"

    That should then apply to overrides of f() too, or else you are breaking the contract.

    The standard might be underspecified on this, but even if it works, I would recommend against it based on readability.

提交回复
热议问题