std::shared_ptr<T>::get
来自cppreference.net
T* get() const noexcept;
|
(直至C++17) | |
element_type* get() const noexcept;
|
(自C++17起) (自C++26起constexpr) |
|
返回存储的指针。
返回值
存储的指针。
注释
一个
shared_ptr
可以在共享对象所有权的同时存储指向另一个对象的指针。
get()
返回的是存储的指针,而非托管的指针。
示例
运行此代码
#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); // 编译器错误 output("Shared pointer: ", &*pShared); // 正确,先调用 operator*,然后取地址 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'; }
可能的输出:
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
参见
|
解引用存储的指针
(公开成员函数) |