[libcxx-commits] [libcxx] [libc++] Mark string functions as [[nodiscard]] (PR #166524)

A. Jiang via libcxx-commits libcxx-commits at lists.llvm.org
Tue Dec 30 03:21:56 PST 2025


================
@@ -1344,24 +1354,26 @@ public:
     return size() == 0;
   }
 
-  _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 const_reference operator[](size_type __pos) const _NOEXCEPT {
+  [[__nodiscard__]] _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 const_reference
+  operator[](size_type __pos) const _NOEXCEPT {
     _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__pos <= size(), "string index out of bounds");
     if (__builtin_constant_p(__pos) && !__fits_in_sso(__pos)) {
       return *(__get_long_pointer() + __pos);
     }
     return *(data() + __pos);
   }
 
-  _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 reference operator[](size_type __pos) _NOEXCEPT {
+  [[__nodiscard__]] _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 reference
+  operator[](size_type __pos) _NOEXCEPT {
     _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(__pos <= size(), "string index out of bounds");
     if (__builtin_constant_p(__pos) && !__fits_in_sso(__pos)) {
       return *(__get_long_pointer() + __pos);
     }
     return *(__get_pointer() + __pos);
   }
 
-  _LIBCPP_CONSTEXPR_SINCE_CXX20 const_reference at(size_type __n) const;
-  _LIBCPP_CONSTEXPR_SINCE_CXX20 reference at(size_type __n);
+  [[__nodiscard__]] _LIBCPP_CONSTEXPR_SINCE_CXX20 const_reference at(size_type __n) const;
+  [[__nodiscard__]] _LIBCPP_CONSTEXPR_SINCE_CXX20 reference at(size_type __n);
----------------
frederick-vs-ja wrote:

> have side effects (i.e. may throw per spec)

I'm not sure whether throwing exception should be considered side effects here. At least it certainly contains no side effect on the `string`.

In most cases, a discarded `s.at(n)` means that one is mentioning an index potentially greater than actually necessary, which doesn't seem correct to me. Perhaps a meaningful usage would be the "checking with `at` once, using `operator[]` later" idiom, I guess. But IMO this looks non-common enough and deserves additional notions.

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


More information about the libcxx-commits mailing list