hn.today

Where to Put [[Nodiscard]]: A Silent Trap with MSVC

giodicanio.com3 points0 comments
Screenshot of Where to Put [[Nodiscard]]: A Silent Trap with MSVC

This describes a compiler bug where placing the nodiscard attribute after storage-specifiers in a function definition causes MSVC to silently ignore it. A simple example: a function declared static with nodiscard following the static specifier returns a value that callers discard, yet MSVC (tested in C++20 mode with /W4 on Visual Studio 2022) emits no warning. Moving the attribute before the static keyword produces the expected warning (warning C4834: discarding return value of function with nodiscard attribute). GCC and Clang correctly diagnose the misplaced attribute and refuse to compile or emit clear diagnostics, so the problem is specific to MSVC’s handling of attribute position.

The practical consequence is a false sense of safety: developers can believe nodiscard guards are active while MSVC silently swallows them depending on attribute placement. The writeup highlights the exact symptom, the differing behavior between compilers, and the expectation that MSVC should warn or reject the misplaced attribute to avoid subtle, hard-to-detect bugs. The upshot is to be careful about attribute order when relying on nodiscard with MSVC and to expect a fix or mitigation from the compiler vendor.

Read on giodicanio.com0 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

OpenCode 2.0

OpenCode 2.0

OpenCode 2.0 introduces a major overhaul with a unified client/server system that runs automatically on users' machines, improving performance and usability. The update includes new features, an improved API, dark mode, and native apps, making the system more flexible and user-friendly. (anoma.ly)

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.