Namespaces
Variants
Views
Actions

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

From cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
 
CharT& back();
(1) (constexpr since C++20)
const CharT& back() const;
(2) (constexpr since C++20)

Returns reference to the last character in the string.

If empty() is true, the behavior is undefined.

(until C++26)

If empty() is true:

  • If the implementation is hardened, a contract violation occurs. Moreover, if the contract-violation handler returns under “observe” evaluation semantic, the behavior is undefined.
  • If the implementation is not hardened, the behavior is undefined.
(since C++26)

Contents

[edit] Return value

operator[](size() - 1)

[edit] Complexity

Constant.

[edit] Notes

In libstdc++, back() is not available in C++98 mode.

[edit] Example

#include <iostream>
#include <string>
 
int main()
{
    std::string s("Exemplary");
    char& back1 = s.back();
    back1 = 's';
    std::cout << s << '\n'; // "Exemplars"
 
    std::string const c("Exemplary");
    char const& back2 = c.back();
    std::cout << back2 << '\n'; // 'y'
}

Output:

Exemplars
y

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 534 C++98 std::basic_string did not have the member function back() added

[edit] See also

(DR*)
accesses the first character
(public member function) [edit]
accesses the last character
(public member function of std::basic_string_view<CharT,Traits>) [edit]