std::basic_string::at(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸŽ€ 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_range if pos >= 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 of std::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