W3cubDocs

/C++

std::shared_ptr::get

T* get() const noexcept;
(until C++17)
element_type* get() const noexcept;
(since C++17)

Returns the stored pointer.

Parameters

(none).

Return value

The stored pointer.

Notes

A shared_ptr may share ownership of an object while storing a pointer to another object. get() returns the stored pointer, not the managed pointer.

Example

#include <iostream>
#include <memory>
#include <string>
 
typedef std::shared_ptr<int> IntPtr;
 
void output(const std::string& msg, int* pInt)
{
    std::cout << msg << *pInt << "\n";
}
 
int main()
{
    int* pInt = new int(42);
    IntPtr pShared(new int(42));
 
    output("Naked pointer ", pInt);
    // output("Shared pointer ", pShared); // compiler error
    output("Shared pointer with get() ", pShared.get());
 
    delete pInt;
}

Output:

Naked pointer 42
Shared pointer with get() 42

See also

dereferences the stored pointer
(public member function)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/memory/shared_ptr/get