-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathweak_ptr_demo.cpp
More file actions
43 lines (34 loc) · 779 Bytes
/
weak_ptr_demo.cpp
File metadata and controls
43 lines (34 loc) · 779 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// demo of shared_ptr
/**
* Modified from cppreference.com's demo code of std::weak_ptr:
* https://en.cppreference.com/w/cpp/memory/weak_ptr
*/
#include <iostream>
#include <memory>
// using std::shared_ptr;
// using std::weak_ptr;
// using std::make_shared;
#include "smart_ptr.hpp"
using smart_ptr::shared_ptr;
using smart_ptr::weak_ptr;
using smart_ptr::make_shared;
weak_ptr<int> gw;
void observe()
{
std::cout << "use_count == " << gw.use_count() << ": ";
if (auto spt = gw.lock()) { // Has to be copied into a shared_ptr before usage
std::cout << *spt << "\n";
}
else {
std::cout << "gw is expired\n";
}
}
int main()
{
{
auto sp = make_shared<int>(42);
gw = sp;
observe();
}
observe();
}