Map: Operator[] Should Be Nodiscard

https://news.ycombinator.com/rss Hits: 5
Summary

Lately libc++ has been adding the C++17 [[nodiscard]] attribute aggressively to every header. (I’m not sure why this month, but my guess is that libc++ just dropped support for some old compiler such that all their supported compilers now permit the attribute even in C++11 mode.) libc++ is following the trail that Microsoft STL has blazed since VS 15.6 in late 2017. Some functions, like malloc, always make sense to mark [[nodiscard]]. Others, like unique_ptr::release, are deliberately left unmarked because even though it is usually a bug to write sometimes that’s actually what you meant — you’re calling it only for its side effect. Back in 2022, Stephan T. Lavavej estimated of unique_ptr::release that “90% of discards are a bug, but 10% are maybe valid… Even though it would find bugs, the cost in false positives is too great.” However, I think it’s worth pointing out that the fix for a false positive is trivial: all you have to do is refactor that line of code into and the warning goes away. So personally I’d apply [[nodiscard]] even to unique_ptr::release. But it would clearly create noise to apply [[nodiscard]] to, for example, printf (which returns int) or vector::erase (which returns an iterator). An interesting borderline case came up this week. In llvm-project#169971, Hristo Hristov marked libc++’s map::operator[] as nodiscard. The assumption was that it is usually a bug to write Hans Wennborg quickly reported that actually Google’s codebases do this a fair bit. Statements calling map::operator[] purely for its side-effect are found in Chromium: // Map the result id to the empty set. combinator_ops_[extension->result_id()]; in V8: // We need to insert the load into the truncation mapping as a key, because // all loads need to be revisited during processing. int32_truncated_loads_[op_idx]; and even in flatbuffers: if (attributes.Add(kv->key()->str(), value)) { delete value; return false; } parser.known_attributes_[kv->key()->str()]; This last example doesn’t ev...

First seen: 2025-12-24 12:44

Last seen: 2025-12-24 16:45