Skip to content

Commit 07a3dd3

Browse files
committed
test08.cpp
1 parent 3083932 commit 07a3dd3

2 files changed

Lines changed: 86 additions & 1 deletion

File tree

section2/test07.cpp

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ class DemoClass final
5151
private:
5252
using mutex_type = int; // dummy type
5353
private:
54-
mutex_type m_mutex;
54+
mutable mutex_type m_mutex;
5555

5656
const long MAX_SIZE = 256;
5757
int m_value;
@@ -60,6 +60,11 @@ class DemoClass final
6060
{
6161
return m_value;
6262
}
63+
64+
void save_data() const
65+
{
66+
m_mutex++;
67+
}
6368
};
6469

6570

section2/test08.cpp

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
// Copyright (c) 2020 by Chrono
2+
//
3+
// g++ test08.cpp -std=c++11 -o a.out;./a.out
4+
// g++ test08.cpp -std=c++14 -o a.out;./a.out
5+
// g++ test08.cpp -std=c++14 -I../common -o a.out;./a.out
6+
7+
#include <cassert>
8+
9+
#include <iostream>
10+
#include <memory>
11+
#include <string>
12+
13+
template<class T, class... Args>
14+
std::unique_ptr<T>
15+
my_make_unique(Args&&... args)
16+
{
17+
return std::unique_ptr<T>(
18+
new T(std::forward<Args>(args)...));
19+
}
20+
21+
void case1()
22+
{
23+
using namespace std;
24+
25+
unique_ptr<int> ptr1(new int(10));
26+
assert(*ptr1 = 10);
27+
assert(ptr1 != nullptr);
28+
29+
unique_ptr<string> ptr2(new string("hello"));
30+
assert(*ptr2 == "hello");
31+
assert(ptr2->size() == 5);
32+
33+
//ptr1++;
34+
//ptr2 += 2;
35+
36+
//unique_ptr<int> ptr3;
37+
//*ptr3 = 42;
38+
39+
auto ptr3 = make_unique<int>(42);
40+
assert(ptr3 && *ptr3 == 42);
41+
42+
auto ptr4 = make_unique<string>("god of war");
43+
assert(!ptr4->empty());
44+
45+
auto ptr5 = my_make_unique<long>(100L);
46+
assert(*ptr5 == 100);
47+
}
48+
49+
void case2()
50+
{
51+
using namespace std;
52+
53+
auto ptr1 = make_unique<int>(42);
54+
assert(ptr1 && *ptr1 == 42);
55+
56+
auto ptr2 = std::move(ptr1);
57+
assert(!ptr1 && ptr2);
58+
}
59+
60+
void case3()
61+
{
62+
using namespace std;
63+
64+
auto ptr1 = make_shared<int>(42);
65+
assert(ptr1 && *ptr1 == 42);
66+
67+
auto ptr2 = make_shared<string>("god of war");
68+
assert(!ptr2->empty());
69+
}
70+
71+
int main()
72+
{
73+
using namespace std;
74+
75+
case1();
76+
case2();
77+
case3();
78+
79+
cout << "smart_ptr demo" << endl;
80+
}

0 commit comments

Comments
 (0)