std::basic_...:operator[](3)

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

okay so welcome to std::basic_...:operator[](3) from the C++ Standard Libary manual β€” this is the page for std::basic_string_view::operator[], and bestie, it's giving β€œtiny function, big main-character energy” ✨

🌸 NAME 🌸

std::basic_string_view::operator[] β€” yep, literally std::basic_string_view::operator[] πŸ’…

πŸ¦‹ Synopsis πŸ¦‹

constexpr const_reference operator[]( size_type pos ) const;  (since C++17)

Returns a const reference to the character at the specified location pos. Since C++17, no cap 🫢

⚠️ No bounds checking is performed: the behavior is undefined if pos >= size(). Like, not β€œoopsie” undefined β€” actual undefined behavior. Do not play with her πŸ’€

πŸ’– Parameters πŸ’–

  • pos β€” position of the character to return

πŸ‘‘ Return value πŸ‘‘

Const reference to the requested character. Periodt.

πŸ’€ Exceptions πŸ’€

Does not throw. She’s chill like that.

⚑ Complexity ⚑

Constant.

🌸 Notes 🌸

Unlike std::basic_string::operator[], std::basic_string_view::operator[](size()) has undefined behavior instead of returning CharT(). This is the messy little difference, iykyk 😭

πŸŽ€ Example πŸŽ€

// Run this code

#include <iostream>
#include <string_view>

int main()
{
    std::string str = "Exemplar";
    std::string_view v = str;
    std::cout << v[2] << '\n';
//  v[2] = 'y'; // Error: cannot modify through a string view
    str[2] = 'y';
    std::cout << v[2] << '\n';
}

Output:

e
y

🌈 See also 🌈

  • at β€” accesses the specified character with bounds checking (public member function)
  • operator[] β€” accesses the specified character (public member function of std::basic_string<CharT,Traits,Allocator>)

mwah πŸ’‹ this iconic little page came from http://cppreference.com, dated 2024.06.10 β€” catch you in the next manpage, bestie πŸ«ΆπŸ’–

πŸ“¦ where this page comes from