C++ Library Extensions 2022.12.09
To help learn modern C++ programming
01-unique_ptr.cpp
Go to the documentation of this file.
1#include <tpf_output.hpp>
2
3#include <memory> // for std::unique_ptr
4
5/*
6 In this episode, we will learn how to pass / return std::unique_ptr to / from a function.
7
8 Please note that std::unique_ptr is declared in the header <memory>
9 */
10
13
14// this function take_unique_ptr_by_value() takes a parameter
15// of type unique_ptr by value.
16// this function is called "the callee"
17void take_unique_ptr_by_value(std::unique_ptr<int> uptr)
18{
19
20 stream <<"The deferenced value of uptr = " << *uptr << endl;
21
22 // uptr goes of this function block,
23 // its memory is destroyed.
24}
25
26// this function pass_unique_ptr_to_a_funcion_by_value() is called
27// the caller.
29{
30 auto p1 = std::make_unique<int>(1);
31
32 // std::unique_ptr does not provide copy constructor / copy assignment
33 // so this line of code does not work
34 // take_unique_ptr_by_value(p1);
35
36 // we have to transfer the ownership of unique_ptr
37 // when we pass a unique_ptr to a function by value.
38 take_unique_ptr_by_value( std::move(p1) );
39 // because we call take_unique_ptr_by_value( std::move(p1) )
40 // by value, transferring the ownership of p1
41
42 // WARNING: After passing unique_ptr to a function,
43 // the caller, in this case, pass_unique_ptr_to_a_funcion_by_value()
44 // should not access the unique_ptr any longer.
45
46 // So, you are causing trouble in the following line of code
47
48 // int a = *p1; // this code causes application crash.
49
50 // stream <<"Wow, not crashed! Really?" << endl;
51
52
53 // if you want to test the validity of unique_ptr
54 // you can do this
55
56 if(p1) // test if p1 is valid
57 {
58 stream <<"Wow, p1 is valid" << endl;
59 }
60 else
61 {
62 stream << "unique_ptr p1 is no longer valid" << endl;
63 }
64
65}
66
68{
69 auto p1 = std::make_unique<int>(10);
70
71 // clone p1 and pass the cloned p1 to
72 // take_unique_ptr_by_value()
73 take_unique_ptr_by_value( std::make_unique<int>( *p1 ) );
74
75 // since we passed cloned p1 to take_unique_ptr_by_value()
76 // the original p1 is still valid at this line of code
77
78 stream <<"p1 is still valid: " << *p1 << endl;
79
80 // we are cloning p1 and assign the cloned to p2
81 // p1 and p2 are distinct object.
82 auto p2 = std::make_unique<int>( *p1 );
83
84 stream <<"the value of p2 after cloned: " << *p2 << endl;
85
86 *p2 = 20;
87
88 stream <<"the value of p1: " << *p1 << endl;
89 stream <<"the value of p2: " << *p2 << endl;
90
91}
92int main()
93{
94 // pass_unique_ptr_to_a_funcion_by_value();
95
97}
void pass_unique_ptr_to_a_funcion_by_value()
void take_unique_ptr_by_value(std::unique_ptr< int > uptr)
tpf::sstream stream
void test_cloning_unique_ptr()
auto endl
int main()
constexpr auto endl
Definition: tpf_output.hpp:973
Stream output operators << are implemented.