What mutation, bounds, null-termination, contiguity, and invalidation guarantees does std::string provide through operator[], at(), data(), and mutating operations?
Show answer and explanation
A non-const string exposes mutable characters at indices below size through operator[] and at; at checks the index and throws out_of_range, while operator[] requires the caller to respect its bounds contract. Since C++17, non-const data returns writable contiguous storage, and data()[size()] is the null terminator; mutate only the actual character range and do not use that pointer to change size or capacity. A write through a valid character reference keeps the string's size unchanged. Operations that can reallocate, such as growth beyond capacity, invalidate pointers, references, and iterators into the old storage; erase and other mutations have operation-specific invalidation rules, so reacquire borrowed handles after structural changes. A pointer from c_str or data remains owned by the string and must not outlive it. Use at at untrusted index boundaries and operator[] after bounds have already been established.
A non-const string exposes mutable characters at indices below size through operator[] and at; at checks the index and throws out_of_range, while operator[] requires the caller to respect its bounds contract. Since C++17, non-const data returns writable contiguous storage, and data()[size()] is the null terminator; mutate only the actual character range and do not use that pointer to change size or capacity. A write through a valid character reference keeps the string's size unchanged. Operations that can reallocate, such as growth beyond capacity, invalidate pointers, references, and iterators into the old storage; erase and other mutations have operation-specific invalidation rules, so reacquire borrowed handles after structural changes. A pointer from c_str or data remains owned by the string and must not outlive it. Use at at untrusted index boundaries and operator[] after bounds have already been established.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.