std::shared...:operator->(3)

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

πŸ’… std::shared...:operator->(3) β€” C++ Standard Libary πŸ’…

okay so welcome to the page for std::shared_ptr’s dereference besties πŸ’– this one is about std::shared_ptr::operator* and std::shared_ptr::operator->, and yes, both of them are since C++11. let’s get into it, no cap 🫢


✨ NAME ✨

std::shared_ptr::operator*,std::shared_ptr::operator-> - std::shared_ptr::operator*,std::shared_ptr::operator->


🌸 Synopsis 🌸

both are const noexcept, and both are since C++11:

T& operator*() const noexcept;  (1) (since C++11)
T* operator->() const noexcept; (2) (since C++11)

these bad boys dereference the stored pointer. the behavior is undefined if the stored pointer is null 😭 not a vibe, not a maybe β€” actual undefined behavior, bestie. do not play with that.


πŸŽ€ Parameters πŸŽ€

(none) β€” literally zero arguments. nothing. nada. the void is empty and we love that for them ✨


πŸ’– Return value πŸ’–

  1. the result of dereferencing the stored pointer, i.e. *get().
  2. the stored pointer, i.e. get().

✨ Remarks ✨

  • when T is an array type or (possibly cv-qualified) (since C++17) void, it is unspecified whether function (1) is declared. if it is declared, it is unspecified what its return type is, except that the declaration (although not necessarily the definition) of the function shall be well formed. this makes it possible to instantiate std::shared_ptr<void> πŸ‘€
  • when T is an array type, it is unspecified whether function (2) is declared. if it is declared, it is unspecified what its return type (since C++17) is, except that the declaration of the function shall be well-formed.

πŸ“ Example πŸ“

run it: // Run this code

#include <iostream>
#include <memory>

struct Foo
{
    Foo(int in) : a(in) {}
    void print() const
    {
        std::cout << "a = " << a << '\n';
    }
    int a;
};

int main()
{
    auto ptr = std::make_shared<Foo>(10);
    ptr->print();
    (*ptr).print();
}

🌈 Output 🌈

a = 10
a = 10

πŸ‘‘ See also πŸ‘‘

  • get β€” returns the stored pointer (public member function)

mwah πŸ’‹ this one’s from http://cppreference.com, dated 2024.06.10, and the page is std::shared...:operator->(3). periodt. 🫢

πŸ“¦ where this page comes from