-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathG35_Decorator_2.cpp
More file actions
82 lines (64 loc) · 2.35 KB
/
G35_Decorator_2.cpp
File metadata and controls
82 lines (64 loc) · 2.35 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
/**************************************************************************************************
*
* \file G35_Decorator_2.cpp
* \brief Guideline 35: Use Decorators to Add Customization Hierarchically
*
* Copyright (C) 2022 Klaus Iglberger - All Rights Reserved
*
* This file is part of the supplemental material for the O'Reilly book "C++ Software Design"
* (https://www.oreilly.com/library/view/c-software-design/9781098113155/).
*
**************************************************************************************************/
//---- <CustomAllocator.h> ----------------
#include <cstdlib>
#include <memory_resource>
class CustomAllocator : public std::pmr::memory_resource
{
public:
CustomAllocator( std::pmr::memory_resource* upstream )
: upstream_{ upstream }
{}
private:
void* do_allocate( size_t bytes, size_t alignment ) override
{
return malloc( bytes );
}
void do_deallocate( void* ptr, [[maybe_unused]] size_t bytes,
[[maybe_unused]] size_t alignment ) override
{
free( ptr );
}
bool do_is_equal(
std::pmr::memory_resource const& other ) const noexcept override
{
return ( this == &other ) ||
( dynamic_cast<const CustomAllocator*>( &other ) != nullptr );
}
std::pmr::memory_resource* upstream_{};
};
//---- <Main.cpp> ---------------------------------------------------------------------------------
#include <array>
#include <cstddef>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <memory_resource>
#include <string>
#include <vector>
int main()
{
/*
std::array<std::byte,1000> raw; // Note: not initialized!
std::pmr::monotonic_buffer_resource buffer{ raw.data(), raw.size(), std::pmr::null_memory_resource() };
*/
CustomAllocator custom_allocator{ std::pmr::new_delete_resource() };
std::pmr::monotonic_buffer_resource buffer{ &custom_allocator };
std::pmr::vector<std::pmr::string> strings{ &buffer };
strings.emplace_back( "String longer than what SSO can handle" );
strings.emplace_back( "Another long string that goes beyond SSO" );
strings.emplace_back( "A third long string that cannot be handled by SSO" );
for( const auto& s : strings ) {
std::cout << std::quoted(s) << '\n';
}
return EXIT_SUCCESS;
}