Namespaces
Variants
Views
Actions

Talk:cpp/string/basic string/operator at

From cppreference.com
< Talk:cpp‎ | string/basic string
Revision as of 07:09, 3 June 2022 by Ybab321 (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

[edit] .size() (expanded via resize()) vs .capacity() (expanded via reserve()):

This page states: "If pos > size(), the behavior is undefined.". What about calling `.reserve()` on the string to reserve storage space? Does that also work? It seems to be that if `capacity()` is sufficiently large--not just `size()`, then you could write into those bytes too, no? ERCaGuy (Gabriel Staples) (talk) 17:09, 2 June 2022 (PDT)

I did a bunch of testing. .reserve() is not sufficient. See my answer here: https://stackoverflow.com/a/72485404/4561887 and test code here: https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/cpp/string__use_std_string_as_a_c_str_buffer.cpp. So, the page is correct as-is, stating that .size() must match. ERCaGuy (Gabriel Staples) (talk) 23:22, 2 June 2022 (PDT)
More directly, accessing a string out of bounds is UB because it violates a specified precondition of the function [1] --Ybab321 (talk) 08:09, 3 June 2022 (PDT)