-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlacementNew.cpp
More file actions
104 lines (79 loc) · 1.79 KB
/
PlacementNew.cpp
File metadata and controls
104 lines (79 loc) · 1.79 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
102
103
104
/**
* \file PlacementNew.cpp
* \brief Placement new allows you to construct an object on memory that's already allocated
*/
#include <StdStream/StdStream.h>
#include <StdTest/StdTest.h>
#include <Stl.h>
//-------------------------------------------------------------------------------------------------
class A
{
public:
explicit A(const std::size_t a_x) :
_x{a_x}
{
STD_TRACE_FUNC;
}
~A()
{
STD_TRACE_FUNC;
}
private:
const std::size_t _x {};
};
//-------------------------------------------------------------------------------------------------
int main(int, char **)
{
// sample 1
{
std::cout << "Sample #1:" << std::endl;
const std::size_t n = 5;
auto *buff = static_cast<A *>(operator new[] (n * sizeof(A)));
for (std::size_t i = 0; i < n; ++ i) {
const std::size_t x = std::rand();
// здесь память для объекта не выделяется, но инициализируется
new (buff + i) A(x);
}
// деинициализация памяти
{
for (std::size_t i = 0; i < n; ++ i) {
buff[i].~A();
}
operator delete[] (buff);
}
}
// sample 2
{
std::cout << "\nSample #2:" << std::endl;
using T = char;
const std::size_t n = 7;
// allocate memory
T *buff = new T[n * sizeof(T)];
// construct in allocated storage ("place")
T *ptr = new (buff) T;
// test
std::strcpy(ptr, "ABCDEF");
std::cout << "\t" << STD_TRACE_VAR(ptr) << std::endl;
// destruct
ptr->~T();
// deallocate memory
delete [] buff;
}
return EXIT_SUCCESS;
}
//-------------------------------------------------------------------------------------------------
#if OUTPUT
Sample #1:
::: A :::
::: A :::
::: A :::
::: A :::
::: A :::
::: ~A :::
::: ~A :::
::: ~A :::
::: ~A :::
::: ~A :::
Sample #2:
ptr: ABCDEF
#endif