Why is C++0x's `noexcept` checked dynamically?

后端 未结 6 1553
抹茶落季
抹茶落季 2020-12-14 15:59

I am curious about the rationale behind noexcept in the C++0x FCD. throw(X) was deprecated, but noexcept seems to do the same thing. I

6条回答
  •  自闭症患者
    2020-12-14 16:31

    As other answers have stated, statements such as dynamic_casts can possibly throw but can only be checked at runtime, so the compiler can't tell for certain at compile time.

    This means at compile time the compiler can either let them go (ie. don't compile-time check), warn, or reject outright (which wouldn't be useful). That leaves warning as the only reasonable thing for the compiler to do.

    But that's still not really useful - suppose you have a dynamic_cast which for whatever reason you know will never fail and throw an exception because your program is written so. The compiler probably doesn't know that and throws a warning, which becomes noise, which probably just gets disabled by the programmer for being useless, negating the point of the warning.

    A similar issue is if you have a function which is not specified with noexcept (ie. can throw exceptions) which you want to call from many functions, some noexcept, some not. You know the function will never throw in the circumstances called by the noexcept functions, but again the compiler doesn't: more useless warnings.

    So there's no useful way for the compiler to enforce this at compile time. This is more in the realm of static analysis, which tend to be more picky and throw warnings for this kind of thing.

提交回复
热议问题