-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweak_ptr.cpp
More file actions
31 lines (29 loc) · 802 Bytes
/
weak_ptr.cpp
File metadata and controls
31 lines (29 loc) · 802 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
#include <memory>
#include <iostream>
#include <unordered_map>
class Widget {};
struct WidgetID {};
std::unique_ptr<const Widget> LoadWidget(WidgetID /*id*/) {}
std::shared_ptr<const Widget> FastLoadWidget(WidgetID id) {
static std::unordered_map<WidgetID, std::weak_ptr<const Widget>> cache;
auto spw = cache[id].lock();
if (!spw) {
spw = LoadWidget(id);
cache[id] = spw;
}
return spw;
}
int main() {
auto spw = std::make_shared<Widget>();
std::cout << spw.use_count() << '\n';
std::weak_ptr<Widget> wpw(spw);
std::cout << spw.use_count() << '\n';
std::cout << wpw.use_count() << '\n';
spw = nullptr;
std::cout << spw.use_count() << '\n';
if (wpw.expired())
std::cout << "expired\n";
auto spw2 = wpw.lock();
std::shared_ptr<Widget> spw3(wpw);
return 0;
}