std::basic_string::at(3)
π std::basic_string::at(3) β C++ Standard Libary bestie page π
okay so this is the std::basic_string::at(3) page from the C++ Standard Libary β yes, thatβs the manual name, and weβre rolling with it. π
Itβs all about grabbing one character from a basic_string with bounds checking, and honestly? iconic behavior.
π NAME π
std::basic_string::at - std::basic_string::at
thatβs it, thatβs the name. recursive main character energy, but we move. β¨
β¨ Synopsis β¨
CharT& at( size_type pos ); (1) (constexpr since C++20)
const CharT& at( size_type pos ) const; (2) (constexpr since C++20)
okay so this function returns a reference to the character at specified location pos. Bounds checking is performed, and an exception of type std::out_of_range will be thrown on invalid access. no silent chaos, periodt. π₯
πΈ Parameters πΈ
posβ position of the character to return. thatβs the one, bestie.
π¦ Return value π¦
Reference to the requested character. simple, iconic, done. β¨
π Exceptions π
- Throws
std::out_of_rangeifpos >= size(). do not ignore this. π¨ - If an exception is thrown for any reason, these functions have no effect (strong exception safety guarantee). so even when it goes wrong, it leaves your string alone β we love a clean exit. π
β‘ Complexity β‘
Constant. no scaling drama, just constant. π
π§ Example π§
// Run this code
#include <iostream>
#include <stdexcept>
#include <string>
int main()
{
std::string s("message"); // for capacity
s = "abc";
s.at(2) = 'x'; // OK
std::cout << s << '\n';
std::cout << "string size = " << s.size() << '\n';
std::cout << "string capacity = " << s.capacity() << '\n';
try
{
// This will throw since the requested offset is greater than the current size.
s.at(3) = 'x';
}
catch (std::out_of_range const& exc)
{
std::cout << exc.what() << '\n';
}
}
π Possible output π
abx
string size = 3
string capacity = 7
basic_string::at
π Defect reports π
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
LWG 847β applied to C++98.- Behavior as published: there was no exception safety guarantee.
- Correct behavior: added strong exception safety guarantee.
π See also π
operator[]β accesses the specified character (public member function).atβ accesses the specified character with bounds checking (public member function ofstd::basic_string_view<CharT,Traits>).
thatβs the whole page, bestie π«Ά β source: http://cppreference.com, version/date: 2024.06.10, and itβs the std::basic_string::at(3) manual page. go forth and check your bounds π
π
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms