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

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

πŸ’… std::unique_ptr::operator[] β€” the cppreference glow-up

okay so bestie, this page is from the C++ Standard Library manual (yes the libary typo energy is real but we move), and it's about one specific lil member function: std::unique_ptr::operator[]. she's the one that lets you poke at individual elements inside an array that a unique_ptr is holding onto. no cap, she's lowkey iconic for array specializations only. πŸŽ€


✨ NAME ✨

std::unique_ptr::operator[] β€” that's literally her name, that's the whole vibe. 🫢


🌸 SYNOPSIS 🌸

here's the signature, copy it exactly bestie:

T& operator[]( std::size_t i ) const;  (since C++11)
                                       (constexpr since C++23)

so operator[] gives you access to the elements of an array that's being managed by a unique_ptr. πŸ¦‹

and now the part where you listen to me: the parameter i shall be less than the number of elements in the array. otherwise? the behavior is undefined. πŸ’€ like, not "throws an exception" undefined, not "returns garbage" undefined β€” full-on undefined, so don't do it, fr fr.

also important: this member function is only provided for specializations for array types. if your unique_ptr isn't pointing at an array, she simply does not exist for you. periodt. ✨


πŸ“ Parameters πŸ“

  • i β€” the index of the element to be returned πŸ’–

πŸ‘‘ Return value πŸ‘‘

returns the element at index i, i.e. get()[i]. that's it, that's the whole deal. slay. 🌈


πŸ”₯ Example πŸ”₯

run this code, bestie, it's a factorial factory:

// Run this code

#include <iostream>
#include <memory>

int main()
{
    const int size = 10;
    std::unique_ptr<int[]> fact(new int[size]);

    for (int i = 0; i < size; ++i)
        fact[i] = (i == 0) ? 1 : i * fact[i - 1];

    for (int i = 0; i < size; ++i)
        std::cout << i << "! = " << fact[i] << '\n';
}

⭐ Output ⭐

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880

look at her go πŸ˜­πŸ’œ nine factorial really said 362880 and meant it.


🧚 See also 🧚

  • get β€” returns a pointer to the managed object (public member function) 🌸

reminder bestie: keep i inside the array size. undefined behavior is not a vibe check you want to fail. πŸ™ˆ

okay that's the page!! sourced straight from cppreference.com, dated 2024.06.10 β€” that's the version and date, mwah, go forth and index responsibly πŸ’…πŸ’–βœ¨

πŸ“¦ where this page comes from