-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
85 lines (72 loc) · 1.42 KB
/
main.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <string>
#include <memory>
#include <exception>
#include <thread>
using namespace std;
// Box cannot hold nullptr
template<class T>
class Box
{
public:
template <class... Args>
static Box<T> create(Args&&... args)
{
return Box<T>(make_shared<T>(std::forward<Args>(args)...));
}
T * operator-> () const
{
return ptr.operator -> ();
}
private:
Box(const shared_ptr<T> & ptr)
: ptr(ptr)
{}
shared_ptr<T> ptr;
};
struct Test
{
Test(int i, double d, const string & s)
: i(i), d(d), s(s)
{
cout << "Test ctor" << endl;
}
~Test()
{
cout << "Test dtor" << endl;
}
Test(const Test & test) = delete;
Test(Test && test) = delete;
Test & operator = (const Test & test) = delete;
Test & operator = (Test && test) = delete;
int i;
double d;
string s;
};
void print(const Box<Test> & test)
{
// there is no need to check for nullptr
cout << test->i << " " << test->d << " " << test->s << endl;
}
void twice(Box<Test> test)
{
// there is no need to check for nullptr
test->i *= 2;
test->d *= 2;
test->s += test->s;
}
/*
stdout:
Test ctor
42 3.14 hello
84 6.28 hellohello
Test dtor
*/
int main()
{
Box<Test> test = Box<Test>::create(42, 3.14, "hello");
print(test);
thread t(twice, test);
t.join();
print(test);
}