Map: Operator[] Should Be Nodiscard
5 months ago
- #nodiscard
- #C++
- #STL
- libc++ and Microsoft STL have been adding the [[nodiscard]] attribute to functions, with some exceptions like unique_ptr::release.
- map::operator[] was marked as [[nodiscard]] in libc++, but this was reverted due to common usage in codebases like Chromium and flatbuffers.
- The idiom 'mymap[key];' is often used for side effects, but it's unclear and could be replaced with mymap.try_emplace(key) or (void)mymap[key]; for clarity.
- Microsoft STL and libc++ mark operator[] of array, deque, and vector as [[nodiscard]], but not map::operator[] due to existing usage patterns.
- LLVM's internal maps like DenseMap, MapVector, and StringMap do not mark operator[] as [[nodiscard]], but could with minor fixes.
- Recommendation: Replace 'm[k];' with m.try_emplace(k) or (void)m[k]; for better code clarity and maintainability.