std::unique...::operator[](3)
π 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
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms