std::shared_ptr<T>::get
来自cppreference.com
<tbody>
</tbody>
<tbody class="t-dcl-rev ">
</tbody><tbody>
</tbody>
T* get() const noexcept; |
(C++17 前) | |
element_type* get() const noexcept; |
(C++17 起) | |
返回存储的指针。
参数
(无)
返回值
存储的指针。
注解
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 << " 于 " << pInt << '\n';
};
int* pInt = new int(42);
std::shared_ptr<int> pShared = std::make_shared<int>(42);
output("裸指针: ", pInt);
// output("共享指针: ", pShared); // 编译器错误
output("共享指针: ", &*pShared); // OK, 调用 operator*, 然后获取其地址
output("共享指针 get(): ", pShared.get());
delete pInt;
std::cout << "\n演示 shared_ptr 别名构造函数。\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 与 p 共享所有权,但指向 Base2 基类子对象:\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';
}
可能的输出:
裸指针: 42 于 0xacac20
共享指针: 42 于 0xacac50
共享指针 get(): 42 于 0xacac50
演示 shared_ptr 别名构造函数。
q 与 p 共享所有权,但指向 Base2 基类子对象:
p.get(): 0xacac20
q.get(): 0xacac24
&(p->i1): 0xacac20
&(p->i2): 0xacac24
&(p->i3): 0xacac28
&(q->i2): 0xacac24
参阅
| 解引用存储的指针 (公开成员函数) |