You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Description: 'Releases ownership of the managed object from a std::unique_ptr.'
4
+
Subjects:
5
+
- 'Code Foundations'
6
+
- 'Computer Science'
7
+
Tags:
8
+
- 'Memory'
9
+
- 'Pointers'
10
+
- 'Programming'
11
+
- 'Variables'
12
+
CatalogContent:
13
+
- 'learn-c-plus-plus'
14
+
- 'paths/computer-science'
15
+
---
16
+
17
+
The **`release()`** function is a member function of smart pointer class `std::unique_ptr`. It releases ownership of the managed object and returns the raw pointer to that object. After calling `release()` the smart pointer becomes empty and holds `nullptr`.
18
+
19
+
## Syntax
20
+
21
+
```cpp
22
+
std::unique_ptr<int> ptr(new int(10));
23
+
int* raw_pointer = ptr.release();
24
+
```
25
+
26
+
The code snippet above creates a `unique_ptr` managing a new integer with a value of 10. Calling `release()` relinquishes ownership and returns the raw pointer, which is assigned to `raw_pointer`.
27
+
28
+
### Parameters
29
+
30
+
The function takes no parameters.
31
+
32
+
### Return value
33
+
34
+
Returns the raw pointer to the object managed by the `unique_ptr` before the call.
35
+
36
+
### Notes
37
+
38
+
After calling `release()`, the caller is responsible for managing the lifetime of the returned raw pointer, including deleting it when no longer needed to prevent memory leaks.
39
+
40
+
## Example
41
+
42
+
The following demonstrates how to use `release()`:
43
+
44
+
```cpp
45
+
#include <iostream>
46
+
#include <memory>
47
+
48
+
int main() {
49
+
50
+
// Create a unique_ptr managing a new int
51
+
std::unique_ptr<int> auto_pointer (new int);
52
+
53
+
// Raw pointer to hold the released pointer
54
+
int* manual_pointer;
55
+
56
+
// Assign value 10 to the managed object
57
+
*auto_pointer = 10;
58
+
59
+
// Release ownership and get the raw pointer
60
+
manual_pointer = auto_pointer.release();
61
+
62
+
// Output the value pointed to by manual_pointer
63
+
std::cout << "manual_pointer now points to " << *manual_pointer << "\n";
64
+
65
+
// Manually delete the raw pointer to avoid memory leak
66
+
delete manual_pointer;
67
+
68
+
return 0;
69
+
}
70
+
```
71
+
72
+
This example creates a unique_ptr called auto_pointer. It manages a dynamically allocated integer and assigns a value of 10 to the object. `Release()` is then used to relinquish ownership and assign the raw pointer to `manual_pointer`. The program prints the value and then manually deletes the raw pointer to avoid a memory leak.
0 commit comments