-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
011_memory_to_address.cpp
95 lines (77 loc) · 1.44 KB
/
011_memory_to_address.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
95
template<class T>
class P1 {
public:
explicit P1(T* p)
: p_(p) { }
T* operator->() const noexcept {
return p_;
}
private:
T* p_;
};
template<class T>
class P2 {
public:
explicit P2(T* p)
: p_(p) { }
P1<T> operator->() const noexcept {
return p_;
}
private:
P1<T> p_;
};
template<class T>
class P3 {
public:
explicit P3(T* p)
: p_(p) { }
T* get() const noexcept {
return p_;
}
private:
T* p_;
};
namespace std {
template<class T>
struct pointer_traits<P3<T> > {
static T* to_address(const P3<T>& p) noexcept {
return p.get();
}
};
} // std
template<class T>
class P4 {
public:
explicit P4(T* p)
: p_(p) { }
T* operator->() const noexcept {
return nullptr;
}
T* get() const noexcept {
return p_;
}
private:
int* p_;
};
namespace std {
template<class T>
struct pointer_traits<P4<T> > {
static T* to_address(const P4<T>& p) noexcept {
return p.get();
}
};
} // std
void test_to_address02() {
int i = 0;
assert(std::to_address(&i) == &i);
int* p = &i;
assert(std::to_address(p) == &i);
P1<int> p1(&i);
assert(std::to_address(p1) == &i);
P2<int> p2(&i);
assert(std::to_address(p2) == &i);
P3<int> p3(&i);
assert(std::to_address(p3) == &i);
P4<int> p4(&i);
assert(std::to_address(p4) == &i);
}