00 //============================================================================
01 // Name        : smart_pointers.cpp
02 // Author      : Simonas Saltenis
03 // Description : smart pointer examples
04 //============================================================================
05 
06 #include "digraph.h"
07 #include <memory>
08 #include <iostream>
09 
10 using namespace std;
11 
12 unique_ptr<digraph_t> create_graph()
13 {
14     auto g = make_unique<digraph_t>(10);   // 10 is passed as an argument to a constructor
15 
16     g->add_edge({0,0,1});
17     g->add_edge({1,1,2});
18 
19     auto gg = std::move(g);  // move constructor, but here just a pointer, g is null after this
20 
21     gg->add_edge({2,2,3});
22     gg->add_edge({3,3,0});
23 
24     return gg;            // no move constructor due to NRVO (named return value optimization)
25 }
26 
27 
28 int main()
29 {
30     auto g1 = create_graph();
31 
32     auto g2 = g1;   // Error ! Copy construction is not possible
33 
34     weak_ptr<digraph_t> wg;   // weak_ptr
35 
36     {
37         shared_ptr<digraph_t> g3 = create_graph();
38 
39         auto g4 = g3;    // now  it is OK.
40 
41         wg = g4;         // weak_ptr
42 
43         cout << g3.use_count() << endl;
44 
45         g4.reset();
46 
47         cout << g3.use_count() << endl;
48 
49         {
50             auto g5 = wg.lock();    // weak_ptr
51 
52             cout << g3.use_count() << endl;
53         }
54 
55         cout << g3.use_count() << endl;
56     }
57 
58     cout << (wg.expired() ? "expired" : "alive") << endl;   // weak_ptr
59 
60     return 0;
61 }