-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_shared_from_this.cpp
94 lines (77 loc) · 2.11 KB
/
test_shared_from_this.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
86
87
88
89
90
91
92
93
94
#include "../src/shared/shared.h"
#include "../src/weak/weak.h"
#define REQUIRE(b) \
{ \
if (!(b)) { \
std::cout << "WRONG" << std::endl; \
}; \
}
// ----------------------------------------
struct T : public EnableSharedFromThis<T> {};
struct Y : T {};
struct Z : Y {};
void NullDeleter(void *) {}
struct Foo : virtual public EnableSharedFromThis<Foo> {
virtual ~Foo() {}
};
struct Bar : public Foo {
Bar(int) {}
};
void TestSharedFromThis() {
{
SharedPtr<T> t1(new T);
SharedPtr<T> t2(MakeShared<T>());
}
{
int x = 42;
SharedPtr<Bar> t1(new Bar(42));
REQUIRE(t1->SharedFromThis() == t1);
SharedPtr<Bar> t2(MakeShared<Bar>(x));
REQUIRE(t2->SharedFromThis() == t2);
}
{
SharedPtr<Y> p(new Z);
SharedPtr<T> q = p->SharedFromThis();
REQUIRE(p == q);
}
{
T *ptr = new T;
SharedPtr<T> s(ptr);
REQUIRE(!ptr->WeakFromThis().Expired());
{
try {
SharedPtr<T> new_s = ptr->SharedFromThis();
REQUIRE(new_s == s);
} catch (...) {
REQUIRE(false);
}
}
s.Reset();
}
{
T *ptr = new T;
WeakPtr<T> weak;
{
SharedPtr<T> s(ptr);
REQUIRE(ptr->SharedFromThis() == s);
weak = s;
REQUIRE(!weak.Expired());
}
REQUIRE(weak.Expired());
weak.Reset();
}
}
void TestWeakFromThis() {
T *ptr = new T;
const T *cptr = ptr;
static_assert(noexcept(ptr->WeakFromThis()), "Operation must be noexcept");
static_assert(noexcept(cptr->WeakFromThis()), "Operation must be noexcept");
WeakPtr<T> weak = ptr->WeakFromThis();
REQUIRE(weak.Expired());
WeakPtr<const T> my_const_weak = cptr->WeakFromThis();
REQUIRE(my_const_weak.Expired());
SharedPtr<T> sptr(ptr);
weak = ptr->WeakFromThis();
REQUIRE(!weak.Expired());
REQUIRE(weak.Lock().Get() == ptr);
}