-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.cc
executable file
·89 lines (66 loc) · 1.78 KB
/
main.cc
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
#include <cstdlib>
#include <iostream>
#include <memory>
struct AllocationMetrics
{
uint32_t TotalAllocated = 0;
uint32_t TotalFreed = 0;
uint32_t CurrentUsage() { return TotalAllocated - TotalFreed; }
};
static AllocationMetrics s_AllocationMetrics;
void* operator new(std::size_t size)
{
std::clog << "Allocating " << size << " bytes\n";
s_AllocationMetrics.TotalAllocated += size;
return malloc(size);
}
void operator delete(void* memory, std::size_t size) noexcept
{
std::clog << "Freeing " << size << " bytes\n";
s_AllocationMetrics.TotalFreed += size;
free(memory);
}
void operator delete(void* memory)
{
free(memory);
}
class Object {
public:
Object() {
std::clog << "Object()" << std::endl;
}
~Object() {
std::clog << "~Object()" << std::endl;
}
int x, y, z;
};
static void PrintMemoryUsage() {
std::clog << "Memory Usage: " << s_AllocationMetrics.CurrentUsage() << " bytes\n";
}
int main(int argc, char const* argv[]) {
PrintMemoryUsage();
// Memory Usage: 0 bytes
// std::string string = "abcdefghijklmnopqrstuv"; // 22 символа
// new не вызывается.
std::string string = "abcdefghijklmnopqrstuvw"; // 23 символа
// new вызывается:
// Allocating 32 bytes
PrintMemoryUsage();
// Memory Usage: 32 bytes
Object* obj = new Object;
// Allocating 12 bytes
// Object()
PrintMemoryUsage();
// Memory Usage: 44 bytes
{
std::unique_ptr<Object> obj = std::make_unique<Object>();
// Allocating 12 bytes
// Object()
PrintMemoryUsage();
// Memory Usage: 56 bytes
}
// ~Object()
PrintMemoryUsage();
// Memory Usage: 56 bytes
return EXIT_SUCCESS;
}