@@ -22,9 +22,20 @@ class function<R(Args...)> {
22
22
function (const function& other) {
23
23
// 类型擦除了怎么知道other中保存的可调用类型具体是什么?
24
24
// 使用clone可以通过多态找到实际的类型
25
- f = other.f ->clone ();
25
+ if (other.f ->is_small_object ()) {
26
+ other.f ->small_clone (&buffer);
27
+ f = &buffer;
28
+ } else {
29
+ f = other.f ->big_clone ();
30
+ }
26
31
}
27
- function (function&& other): f(other.f) {
32
+ function (function&& other) {
33
+ if (other.f ->is_small_object ()) {
34
+ other.f ->small_clone (&buffer);
35
+ f = &buffer;
36
+ } else {
37
+ f = other.f ;
38
+ }
28
39
other.f = nullptr ;
29
40
}
30
41
@@ -47,12 +58,15 @@ class function<R(Args...)> {
47
58
return (*f)(hstl::forward<Args>(args)...);
48
59
}
49
60
private:
61
+ static constexpr size_t BufferSize = sizeof (void *) * 3 ;
50
62
struct FuncBase {
51
63
virtual R operator ()(Args... args) = 0;
52
64
// 由于类型擦除,存放的可调用对象F的具体类型是不知道的,
53
65
// clone用于实际的可调用对象类型F的拷贝,类似于工厂方法,
54
66
// 这里的工厂就是自己
55
- virtual FuncBase* clone () = 0;
67
+ virtual FuncBase* big_clone () = 0;
68
+ virtual void small_clone (void * buffer) = 0;
69
+ virtual constexpr bool is_small_object () = 0;
56
70
virtual ~FuncBase () = default ;
57
71
};
58
72
template <typename F>
@@ -62,16 +76,23 @@ class function<R(Args...)> {
62
76
FuncType f;
63
77
explicit FuncImpl (const FuncType& func): f(func) {}
64
78
explicit FuncImpl (FuncType&& func) : f(hstl::move(func)) {}
65
- FuncBase* clone () override {
79
+ FuncBase* big_clone () override {
66
80
return new FuncImpl (f);
67
81
}
82
+ void small_clone (void * buffer) override {
83
+ ::new (buffer) FuncImpl (f);
84
+ }
85
+ constexpr bool is_small_object () override {
86
+ return sizeof (*this ) <= BufferSize;
87
+ }
88
+
68
89
FuncImpl (const FuncImpl& fi): f(fi.f) {}
69
90
R operator ()(Args... args) override {
70
91
return f (hstl::forward<Args>(args)...);
71
92
}
72
93
};
73
94
74
- std::aligned_storage<sizeof ( void *) * 3 > buffer;
95
+ std::aligned_storage<BufferSize > buffer;
75
96
FuncBase* f;
76
97
};
77
98
0 commit comments