名稱空間
變體
操作

std::shared_ptr<T>::get

來自 cppreference.com
 
 
記憶體管理庫
(僅作說明*)
未初始化記憶體演算法
(C++17)
(C++17)
(C++17)
受約束的未初始化
記憶體演算法
C 庫

分配器
記憶體資源
垃圾回收支援
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化儲存
(直到 C++20*)
(直到 C++20*)
顯式生命週期管理
 
 
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 << " 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';
}

可能的輸出

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

[編輯] 參閱

解引用儲存的指標
(公共成員函式) [編輯]