-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.cc
90 lines (74 loc) · 2.02 KB
/
test.cc
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
86
87
88
89
90
#include <gtest/gtest.h>
#include <thread>
#include "my_shared_ptr.h"
#include "my_unique_ptr.h"
void thread_content(my_shared_ptr<int>& ptr) {
my_shared_ptr<int> ptr1(ptr);
ASSERT_EQ(ptr1.use_count(), 2);
}
TEST(test_get, my_shared_ptr) {
my_shared_ptr<int> ptr(new int(1));
ASSERT_EQ(*(ptr.get()), 1);
}
TEST(test_reset, my_shared_ptr) {
my_shared_ptr<int> ptr1(new int(1));
ASSERT_EQ(*(ptr1.get()), 1);
ptr1.reset(new int(5));
ASSERT_EQ(*(ptr1.get()), 5);
ptr1.reset();
ASSERT_EQ(ptr1.get(), nullptr);
}
TEST(test_use_count, my_shared_ptr) {
my_shared_ptr<int> ptr(new int(1));
ASSERT_EQ(ptr.use_count(), 1);
my_shared_ptr<int> ptr1(ptr);
ASSERT_EQ(ptr.use_count(), 2);
{
my_shared_ptr<int> ptr2(ptr);
ASSERT_EQ(ptr.use_count(), 3);
}
ASSERT_EQ(ptr.use_count(), 2);
}
TEST(test_unique_true, my_shared_ptr) {
my_shared_ptr<int> ptr(new int(1));
ASSERT_TRUE(ptr.unique());
}
TEST(test_unique_false, my_shared_ptr) {
my_shared_ptr<int> ptr(new int(1));
my_shared_ptr<int> ptr1(ptr);
ASSERT_FALSE(ptr.unique());
}
TEST(test_observer, my_shared_ptr) {
struct new_int {
int val;
new_int(int value) : val(value) {}
};
my_shared_ptr<new_int> ptr(new new_int(1));
ASSERT_EQ((*ptr).val, 1);
ASSERT_EQ(ptr->val, 1);
}
// Multithreaded read is safe, but once it gets to the raw pointer the
// shared_ptr stores, it becomes dangerous.
TEST(test_multi_thread, my_shared_ptr) {
my_shared_ptr<int> ptr(new int(1));
std::thread t(thread_content, std::ref(ptr));
t.join();
ASSERT_EQ(ptr.use_count(), 1);
}
TEST(test_constructor, my_unique_ptr) {
my_unique_ptr<int> ptr(new int(1));
ASSERT_EQ((*ptr.get()), 1);
}
TEST(test_copy_assign, my_unique_ptr) {
my_unique_ptr<int> ptr(new int(1));
my_unique_ptr<int> ptr2(ptr);
ASSERT_EQ(ptr.get(), nullptr);
my_unique_ptr<int> ptr3 = ptr2;
ASSERT_EQ(ptr2.get(), nullptr);
}
TEST(test_release, my_unique_ptr) {
my_unique_ptr<int> ptr(new int(1));
int* iptr = ptr.release();
ASSERT_EQ(ptr.get(), nullptr);
ASSERT_EQ(*iptr, 1);
}