std::basic_string::front(3)

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

πŸ’– NAME πŸ’–

std::basic_string::front β€” std::basic_string::front.

Opening vibe check: this is the std::basic_string::front(3) page from the C++ Standard Libary manual ✨ (yes, that spelling is in the header, iykyk). We are literally here to talk about the first character of a string, and bestie, it is giving main character energy πŸ‘‘.


πŸ“œ Synopsis πŸ“œ

CharT& front();             (1) (constexpr since C++20)
const CharT& front() const; (2) (constexpr since C++20)

So front() returns a reference to the first character in the string. The behavior is undefined if empty() is true β€” that is the dramatic warning, bestie πŸ’€. Do not test an empty string with this and then act surprised.

Two overloads, both marked (constexpr since C++20) in the synopsis πŸ’….


🫢 Parameters 🫢

(none) β€” no parameters, no arguments, no little extras. Zero. Nada. πŸŽ€


✨ Return value ✨

Reference to the first character, equivalent to operator[](0) 🌟.


⚑ Complexity ⚑

Constant. That is the whole complexity section, and it ate πŸ”₯.


πŸ“ Notes πŸ“

In libstdc++, front() is not available in C++98 mode. That is the note, fr fr πŸ™ˆ.


πŸ§ͺ Example πŸ§ͺ

// Run this code

#include <iostream>
#include <string>

int main()
{
    std::string s("Exemplary");
    char& f1 = s.front();
    f1 = 'e';
    std::cout << s << '\n'; // "exemplary"

    std::string const c("Exemplary");
    char const& f2 = c.front();
    std::cout << &f2 << '\n'; // "Exemplary"
}

Output:

exemplary
Exemplary

The first one gets its first character changed from E to e, and the const one stays iconic and unchanged. Periodt πŸ’œ.


🩹 Defect reports 🩹

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

  • DR LWG 534 β€” applied to C++98.
    • Behavior as published: std::basic_string did not have the member function front().
    • Correct behavior: front() was added.

πŸ‘€ See also πŸ‘€

  • back β€” accesses the last character (DR*) (public member function).
  • front β€” accesses the first character (public member function of std::basic_string_view<CharT,Traits>).

Footer check, bestie: http://cppreference.com, 2024.06.10, and std::basic_string::front(3) β€” source/version plus date, all accounted for πŸ«ΆπŸ’–. Bye bestie, go access that first character responsibly πŸ’…βœ¨.

πŸ“¦ where this page comes from