[clang] [clang] Improve diagnostic on [[nodiscard]] attribute (PR #112521)

Yihe Li via cfe-commits cfe-commits at lists.llvm.org
Wed Oct 16 13:09:10 PDT 2024


Mick235711 wrote:

Release note added.

Incidentally, this also fixes an inconsistency for Clang compared to GCC/MSVC: In the following program
```cpp
struct [[nodiscard("Reason 1")]] S {};
[[nodiscard("Reason 2")]] S getS();

int main()
{
    getS();
}
```
My opinion is that the function's attribute should take precedence since it is "more specific". GCC/MSVC trunk agrees with me and prints Reason 2 in warning, while Clang trunk prints Reason 1. ([Compiler Explorer](https://godbolt.org/z/4jd1zK31j)). After this PR, Clang will also print Reason 2 here.

Also, the same CE link also explores the note generation on `nodiscard` vs `deprecated`, which was the motivation for the original PR #112289. Here, GCC is the most verbose, generating 1 warning + 2 notes (one on declaration of function and one on declaration of type), when the function's return type is marked as `nodiscard`. 1 warning + 1 note is generated for both `deprecated` and normal `nodiscard` on the function itself. MSVC on the other hand just generates 1 warning (no note) for `nodiscard` regardless of placement, and doesn't seem to implemented `deprecated` at all. (This stats is only FYI)

https://github.com/llvm/llvm-project/pull/112521


More information about the cfe-commits mailing list