std::shared_ptr::get(3)
π
std::shared_ptr::get(3) β C++ Standard Libary
Hey bestie, welcome to std::shared_ptr::get(3) from the C++ Standard Libary manual. Buckle up, because this one is short, iconic, and lowkey carrying a whole aliasing plot twist. π
πΈ NAME πΈ
std::shared_ptr::get β std::shared_ptr::get
Yes bestie, the name is literally the name. No notes. π
β¨ Synopsis β¨
T* get() const noexcept; (until C++17)
element_type* get() const noexcept; (since C++17)
Returns the stored pointer.
π Parameters π
- (none) β zero arguments, nada, the parentheses are empty and living their best life. π«Ά
π Return value π
The stored pointer. Full stop. That's the whole return value, no hidden extras. β¨
π¦ Notes π¦
A shared_ptr may share ownership of an object while storing a pointer to another object. Yes, bestie, it can do that β main character energy fr fr.
get() returns the stored pointer, not the managed pointer. Keep that distinction close to your heart. π
π₯ Example π₯
// Run this code
#include <iostream>
#include <memory>
#include <string_view>
int main()
{
auto output = [](std::string_view msg, int const* pInt)
{
std::cout << msg << *pInt << " in " << pInt << '\n';
};
int* pInt = new int(42);
std::shared_ptr<int> pShared = std::make_shared<int>(42);
output("Naked pointer: ", pInt);
// output("Shared pointer: ", pShared); // compiler error
output("Shared pointer: ", &*pShared); // OK, calls operator*, then
takes addr
output("Shared pointer with get(): ", pShared.get());
delete pInt;
std::cout << "\nThe shared_ptr's aliasing constructor demo.\n";
struct Base1 { int i1{}; };
struct Base2 { int i2{}; };
struct Derived : Base1, Base2 { int i3{}; };
std::shared_ptr<Derived> p(new Derived());
std::shared_ptr<Base2> q(p, static_cast<Base2*>(p.get()));
std::cout << "q shares ownership with p, but points to Base2
subobject:\n"
<< "p.get(): " << p.get() << '\n'
<< "q.get(): " << q.get() << '\n'
<< "&(p->i1): " << &(p->i1) << '\n'
<< "&(p->i2): " << &(p->i2) << '\n'
<< "&(p->i3): " << &(p->i3) << '\n'
<< "&(q->i2): " << &(q->i2) << '\n';
}
π Possible output π
Naked pointer: 42 in 0xacac20
Shared pointer: 42 in 0xacac50
Shared pointer with get(): 42 in 0xacac50
The shared_ptr's aliasing constructor demo.
q shares ownership with p, but points to Base2 subobject:
p.get(): 0xacac20
q.get(): 0xacac24
&(p->i1): 0xacac20
&(p->i2): 0xacac24
&(p->i3): 0xacac28
&(q->i2): 0xacac24
π See also π
operator*β dereferences the stored pointeroperator->β (public member function)
Okay bestie, that's the whole page! This little icon comes from http://cppreference.com, version dated 2024.06.10. Now go call get() responsibly and slay the aliasing game π
β¨π¦
π¦ 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