Skip to content

Add .get() term entry for C++ smart pointers with syntax, example #6871 #6874

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions content/cpp/concepts/pointers/terms/get/get.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
---
Title: '.get()'
Description: 'Returns the raw pointer held by a smart pointer in C++.'
Subjects:
- 'Code Foundations'
- 'Computer Science'
Tags:
- 'Pointers'
- 'Memory'
- 'Methods'
CatalogContent:
- 'learn-c-plus-plus'
- 'paths/computer-science'
---

The **`.get()`** method in C++ is used with smart pointers (such as `std::unique_ptr` and `std::shared_ptr`) to access the raw pointer they manage. It allows code to interface with functions or APIs that require traditional pointers, while still preserving the ownership and automatic memory management provided by the smart pointer.

> **Note:** Calling `.get()` returns the raw pointer managed by the smart pointer, but does not transfer ownership. The smart pointer still retains responsibility for managing and deleting the memory.

## Syntax

```pseudo
ptr.get()
```

Where `ptr` is a smart pointer such as `std::unique_ptr<T>` or `std::shared_ptr<T>`.

**Parameters:**

- The `.get()` method takes no parameters.

**Return value:**

- Returns a raw pointer of type `T*` to the managed object.
- The returned pointer does not transfer ownership — the smart pointer still controls the object's lifetime.

## Example

The following example demonstrates how `.get()` is used to access the underlying pointer managed by a `std::unique_ptr`:

```cpp
#include <iostream>
#include <memory>

void printValue(int* ptr) {
if (ptr) {
std::cout << "Value: " << *ptr << std::endl;
}
}

int main() {
std::unique_ptr<int> uptr = std::make_unique<int>(42);

// Pass the raw pointer to a function that expects an int*
printValue(uptr.get());

return 0;
}
```

This example results in the following output:

```shell
Value: 42
```

## Codebyte Example

The following codebyte creates a `std::shared_ptr`, retrieves the raw pointer using `.get()`, and prints its value:

```codebyte/cpp
#include <iostream>
#include <memory>

int main() {
std::shared_ptr<int> sptr = std::make_shared<int>(99);

// Use .get() to access the raw pointer
int* rawPtr = sptr.get();

if (rawPtr) {
std::cout << "Shared pointer value: " << *rawPtr << std::endl;
}

return 0;
}
```