forked from ChunelFeng/CGraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCAllocator.h
More file actions
101 lines (85 loc) · 2.2 KB
/
CAllocator.h
File metadata and controls
101 lines (85 loc) · 2.2 KB
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
96
97
98
99
100
101
/***************************
@Author: Chunel
@Contact: [email protected]
@File: CAllocator.h
@Time: 2024/11/23 21:54
@Desc:
***************************/
#ifndef CGRAPH_CALLOCATOR_H
#define CGRAPH_CALLOCATOR_H
#include <new>
#include <mutex>
#include <memory>
#include "CObject.h"
#include "CStruct.h"
#include "CStdEx.h"
CGRAPH_NAMESPACE_BEGIN
class CAllocator {
public:
/**
* 生成一个 CObject 对象
* @tparam T
* @return T*
*/
template<typename T,
c_enable_if_t<std::is_base_of<CObject, T>::value, int> = 0>
static T* safeMallocCObject() {
return safeMalloc<T>();
}
/**
* 生成一个 CStruct 的对象
* @tparam T
* @return T*
*/
template<typename T,
c_enable_if_t<std::is_base_of<CStruct, T>::value, int> = 0>
static T* safeMallocCStruct() {
return safeMalloc<T>();
}
/**
* 生成带参数的普通指针
* @tparam T
* @tparam Args
* @param args
* @return T*
*/
template<typename T, typename ...Args,
c_enable_if_t<std::is_base_of<CObject, T>::value, int> = 0>
static T* safeMallocTemplateCObject(Args&&... args) {
T* result = nullptr;
while (!result) {
result = new(std::nothrow) T(std::forward<Args&&>(args)...);
}
return result;
}
/**
* 生成unique智能指针信息
* @tparam T
* @return std::unique_ptr<T>
*/
template<typename T,
c_enable_if_t<std::is_base_of<CObject, T>::value, int> = 0>
static std::unique_ptr<T> makeUniqueCObject() {
return c_make_unique<T>();
}
private:
/**
* 生成T类型的对象
* @tparam T
* @return T*
*/
template<class T>
static T* safeMalloc() {
T* ptr = nullptr;
while (!ptr) {
ptr = new(std::nothrow) T();
}
return ptr;
}
};
#define CGRAPH_SAFE_MALLOC_COBJECT(Type) \
CAllocator::safeMallocCObject<Type>(); \
#define CGRAPH_MAKE_UNIQUE_COBJECT(Type) \
CAllocator::makeUniqueCObject<Type>(); \
CGRAPH_NAMESPACE_END
#endif //CGRAPH_CALLOCATOR_H