-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconstruct.h
78 lines (62 loc) · 1.66 KB
/
construct.h
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
//
// Created by gy gao on 8/31/22.
//
#ifndef MYOWNSTL_CONSTRUCT_H
#define MYOWNSTL_CONSTRUCT_H
// 头文件包含两个函数 construct,destroy
// construct : 负责对象的构造
// destroy : 负责对象的析构
#include <new>
#include "type_traits.h"
#include "iterator.h"
namespace myownstl
{
// construct
template<class Ty>
void construct(Ty* ptr)
{
::new ((void *)ptr) Ty();
}
// placement new
template<class Ty1, class Ty2>
void construct(Ty1* ptr, const Ty2& value)
{
::new ((void *)ptr) Ty1(value);
}
template<class Ty, class... Args>
void construct(Ty* ptr, Args&&... args)
{
::new ((void *)ptr) Ty(std::forward<Args>(args)...);
}
// destroy 将对象析构
template<class Ty>
void destroy_one(Ty*, std::true_type) {}
template<class Ty>
void destroy_one(Ty* pointer, std::false_type)
{
if (pointer != nullptr)
{
pointer->~Ty();
}
}
template<class ForwardIter>
void destroy_cat(ForwardIter, ForwardIter, std::true_type) {}
template<class ForwardIter>
void destroy_cat(ForwardIter first, ForwardIter last, std::false_type)
{
for (; first != last; ++first)
destory(&(*first));
}
template<class Ty>
void destroy(Ty* pointer)
{
destory_one(pointer, std::is_trivially_destructible<Ty>{});
}
template<class ForwardIter>
void destroy(ForwardIter first, ForwardIter last)
{
destory_cat(first, last, std::is_trivially_destructible<
typename iterator_traits<ForwardIter>::value_type>{});
}
}
#endif //MYOWNSTL_CONSTRUCT_H