CppCoreGuidelines icon indicating copy to clipboard operation
CppCoreGuidelines copied to clipboard

F.6 usage of "noexcept": exclude virtual inline declarations?

Open kwbBaker opened this issue 1 year ago • 1 comments

Compiler: "Function 'whatever' can be declared 'noexcept'" Me: No, it only appears that way because you're looking at a minimal (or no-op) base class implementation. You are falsely assuming that not throwing exceptions should be part of the interface it demands of all derived classes just because you are looking only at the base class implementation and seeing that it doesn't throw! Derived classes' implementations of 'whatever' may very well need to throw!

After all, isn't "noexcept" considered to be part of the interface that is inherited? Excuse me if I'm ignorant of something contradictory here.

Many times lately (yes, I'm still kind of new to a lot of this) I've tried adding "noexcept" at the suggestion of guideline F.6 only to run into numerous reasons why that was a really bad idea. It suggests that there needs to be some finer subtlety about when that guidance should be issued.

Now I'm wondering if this guideline should limit its application to not apply to virtual methods, especially those whose implementation is being declared inline, since the compiler cannot possibly know whether all derived classes will be equally devoid of any throwing (and an exception to that might be where the guidelines checking is being done across all possible derivatives -- such might be the case when the declaration is in a compilation unit itself instead of an included file, since any derived classes would almost certainly be found in that same file -- but of course the compiler would have to check every such derived class implementation's version of the function to see that all of them are equally non-throwing).

For that matter, I see the suggestion for separated definitions (not inline) where adding the "noexcept" would also require adding it to the declaration (usually in a corresponding .h file), and if that is a virtual function in a class, then it can be just as bad an idea there for the same reason. So maybe "inline" isn't really a necessary part of what should be excluded: just virtual any methods.

kwbBaker avatar Sep 25 '24 16:09 kwbBaker

Editors call: Thanks!

The principle is that virtual functions are primarily designed to provide an interface, and overriders to provide implementations. A noexcept on a base virtual function is establishing a guarantee that all overriders must abide by.

Assigned to @gdr-at-ms to add text to this effect in F.6

hsutter avatar Sep 26 '24 18:09 hsutter

Should F.6 be merged with E.12? It looks like the rules have the same intent, but one is in the function section while the other in error handling.

bgloyer avatar Jan 12 '25 01:01 bgloyer

Fixed in #2264.

hsutter avatar Apr 15 '25 17:04 hsutter