std::basic_string<CharT,Traits,Allocator>::at

Returns a reference to the character at specified location pos. Bounds checking is performed, exception of type std::out_of_range will be thrown on invalid access.

# Declarations

CharT& at( size_type pos );

(constexpr since C++20)

const CharT& at( size_type pos ) const;

(constexpr since C++20)

# Parameters

# Return value

Reference to the requested character.

# Example

#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';
    }
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 847C++98there was no exception safety guaranteeadded strong exception safety guarantee
LWG 2207C++98the behavior was undefined if pos >= size() is truealways throws an exception in this case

# See also