-
Notifications
You must be signed in to change notification settings - Fork 0
/
smart_ptr.cpp
60 lines (47 loc) · 1.75 KB
/
smart_ptr.cpp
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//
// Created by Maria Baburina on 18.10.21.
//
#include <iostream>
#include <memory>
#include <thread>
#include <chrono>
#include <mutex>
#include "smart_ptr.h"
Base::Base() { std::cout << "Base::Base\n"; }
Base::~Base() { std::cout << "Base::Basee\n"; }
void Base::bar() { std::cout << "Base::bar\n"; }
Derived::Derived() { std::cout << " Derived::Derived()\n"; }
Derived::~Derived() { std::cout << " Derived::~Derived()\n"; }
void thr(std::shared_ptr<Base> p) {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::shared_ptr<Base> lp = p; // thread-safe, even though the
// shared use_count is incremented
{
static std::mutex io_mutex;
std::lock_guard<std::mutex> lk(io_mutex);
std::cout << "local pointer in a thread:\n"
<< " lp.get() = " << lp.get()
<< ", lp.use_count() = " << lp.use_count() << '\n';
}
}
void smart_ptr_foo() {
std::unique_ptr<Base> pFoo1(new Base); // p1 owns Base
if (pFoo1)
pFoo1->bar();
std::unique_ptr<Base> pFoo2(move(pFoo1)); // now p2 owns
if (pFoo2) pFoo2->bar();
std::shared_ptr<Base> p = std::make_shared<Derived>();
std::cout << "Created a shared Derived (as a pointer to Base)\n"
<< " p.get() = " << p.get()
<< ", p.use_count() = " << p.use_count() << '\n';
std::thread t1(thr, p), t2(thr, p), t3(thr, p);
p.reset(); // release ownership from main
std::cout << "Shared ownership between 3 threads and released\n"
<< "ownership from main:\n"
<< " p.get() = " << p.get()
<< ", p.use_count() = " << p.use_count() << '\n';
t1.join();
t2.join();
t3.join();
std::cout << "All threads completed, the last one deleted Derived\n";
}