.get()
The .get()
function in C++ is used with smart pointers such as std::unique_ptr
and std::shared_ptr
to obtain the raw pointer to the managed object without transferring ownership. It is commonly used when working with legacy code or APIs that require raw pointers, or when there is a need to access the underlying object directly while still maintaining smart pointer ownership and automatic memory management.
Syntax
ptr.get();
Here, ptr
is a std::unique_ptr<T>
or std::shared_ptr<T>
.
Parameters:
.get()
does not take any parameters.
Return value:
- Returns the raw pointer (
T*
) to the managed object. - Ownership remains with the smart pointer; the caller must not delete the returned pointer.
Example
This example shows how the .get()
method returns a raw pointer to a managed object without transferring ownership:
#include <iostream>#include <memory>int main() {std::unique_ptr<int> uniq_ptr(new int(20));int* raw_ptr = nullptr;raw_ptr = uniq_ptr.get(); // returns pointer to a managed object without transferring ownershipstd::cout << "value at raw_ptr address: " << *raw_ptr << std::endl;return 0;}
The output of this example is:
value at raw_ptr address: 20
In this example:
- The
uniq_ptr
manages a dynamically allocatedint
with a value of 20. - The
.get()
method returns a raw pointer to the managed object, soraw_ptr
points to the same memory location asuniq_ptr
, but without taking ownership. raw_ptr
can access (read or write) the value, whileuniq_ptr
still maintains exclusive ownership and will automatically delete the object when it goes out of scope.
Codebyte Example
This example shows how .get()
can be used to pass a raw pointer to a legacy function that does not accept smart pointers:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours