File: taking_allocators.cpp

package info (click to toggle)
foonathan-memory 0.7-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,748 kB
  • sloc: cpp: 12,014; xml: 139; sh: 49; makefile: 22
file content (312 lines) | stat: -rw-r--r-- 9,102 bytes parent folder | download
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
// Copyright (C) 2015-2020 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.

// this example provides two implementation of a deep_copy_ptr that performs a copy when copying the pointer
// the first version takes an Allocator the second a RawAllocator
// see http://foonathan.github.io/doc/memory/md_doc_internal_usage.html for a step-by-step walkthrough
// I know the class is pretty dumb and not that great designed (copy performs deep copy, move invalidates), but that's not that the point

#include <cassert>
#include <memory>
#include <iostream>

#include <foonathan/memory/allocator_storage.hpp> // allocator_reference
#include <foonathan/memory/default_allocator.hpp> // default_allocator

// alias namespace foonathan::memory as memory for easier access
#include <foonathan/memory/namespace_alias.hpp>

namespace using_std_allocator
{
    template <typename T, class Allocator = std::allocator<T>>
    class deep_copy_ptr : Allocator
    {
        using traits = std::allocator_traits<Allocator>;

    public:
        using value_type     = typename traits::value_type;
        using allocator_type = Allocator;

        explicit deep_copy_ptr(const allocator_type& alloc = allocator_type{})
        : allocator_type(alloc), ptr_(nullptr)
        {
        }

        deep_copy_ptr(value_type value, const allocator_type& alloc = allocator_type{})
        : allocator_type(alloc), ptr_(create(*this, std::move(value)))
        {
        }

        deep_copy_ptr(const deep_copy_ptr& other)
        : allocator_type(traits::select_on_container_copy_construction(other)),
          ptr_(create(*this, *other))
        {
        }

        deep_copy_ptr(deep_copy_ptr&& other) noexcept : allocator_type(std::move(other)),
                                                        ptr_(other.ptr_)
        {
            other.ptr_ = nullptr;
        }

        ~deep_copy_ptr() noexcept
        {
            destroy();
        }

        deep_copy_ptr& operator=(const deep_copy_ptr& other)
        {
            if (traits::propagate_on_container_copy_assignment::value
                && static_cast<Allocator&>(*this) != other)
            {
                allocator_type alloc(other);
                auto           ptr = create(alloc, *other);
                destroy();

                Allocator::operator=(std::move(alloc));
                ptr_               = ptr;
            }
            else
            {
                auto ptr = create(*this, *other);
                destroy();
                ptr_ = ptr;
            }
            return *this;
        }

        deep_copy_ptr& operator=(deep_copy_ptr&& other) noexcept(
            traits::propagate_on_container_move_assignment::value)
        {
            if (traits::propagate_on_container_move_assignment::value
                && static_cast<allocator_type&>(*this) != other)
            {
                allocator_type::operator=(std::move(other));
                ptr_                    = other.ptr_;
                other.ptr_              = nullptr;
            }
            else if (static_cast<allocator_type&>(*this) == other)
            {
                ptr_       = other.ptr_;
                other.ptr_ = nullptr;
            }
            else
            {
                auto ptr = create(*this, std::move(*other));
                destroy();
                ptr_ = ptr;
            }
            return *this;
        }

        friend void swap(deep_copy_ptr& a, deep_copy_ptr& b) noexcept
        {
            using std::swap;
            if (traits::propagate_on_container_swap::value)
                swap(static_cast<allocator_type&>(a), static_cast<allocator_type&>(b));
            else
                assert(static_cast<allocator_type&>(a) == b);
            swap(a.ptr_, b.ptr_);
        }

        explicit operator bool() const
        {
            return !!ptr_;
        }

        T& operator*()
        {
            return *ptr_;
        }

        const T& operator*() const
        {
            return *ptr_;
        }

        typename traits::pointer operator->()
        {
            return ptr_;
        }

        typename traits::const_pointer operator->() const
        {
            return ptr_;
        }

    private:
        template <typename... Args>
        typename traits::pointer create(allocator_type& alloc, Args&&... args)
        {
            auto ptr = traits::allocate(alloc, 1);
            try
            {
                traits::construct(alloc, ptr, std::forward<Args>(args)...);
            }
            catch (...)
            {
                traits::deallocate(alloc, ptr, 1);
                throw;
            }
            return ptr;
        }

        void destroy() noexcept
        {
            if (ptr_)
            {
                traits::destroy(*this, ptr_);
                traits::deallocate(*this, ptr_, 1);
            }
        }

        typename traits::pointer ptr_;
    };
}

namespace using_raw_allocator
{
    template <typename T,
              class RawAllocator =
                  memory::default_allocator> // default allocator type, usually heap_allocator
    class deep_copy_ptr
        : memory::
              allocator_reference<RawAllocator> // store the allocator by reference to allow sharing and copying
    // for stateless allocators like default_allocator, it does not store an actual reference
    // and can take a temporary, for stateful, the allocator must outlive the reference
    {
        using allocator_ref = memory::allocator_reference<RawAllocator>;

    public:
        using value_type     = T;
        using allocator_type = typename allocator_ref::allocator_type;

        explicit deep_copy_ptr(allocator_ref alloc = allocator_type{})
        : allocator_ref(alloc), ptr_(nullptr)
        {
        }

        deep_copy_ptr(value_type value, allocator_ref alloc = allocator_type{})
        : allocator_ref(alloc), ptr_(create(std::move(value)))
        {
        }

        deep_copy_ptr(const deep_copy_ptr& other) : allocator_ref(other), ptr_(create(*other))
        {
        }

        deep_copy_ptr(deep_copy_ptr&& other) noexcept : allocator_ref(std::move(other)),
                                                        ptr_(other.ptr_)
        {
            other.ptr_ = nullptr;
        }

        ~deep_copy_ptr() noexcept
        {
            destroy();
        }

        // assignment uses straightforward copy/move-and-swap idiom, instead of boilerplate required by Allocator
        deep_copy_ptr& operator=(const deep_copy_ptr& other)
        {
            deep_copy_ptr tmp(other);
            swap(*this, tmp);
            return *this;
        }

        deep_copy_ptr& operator=(deep_copy_ptr&& other) noexcept
        {
            deep_copy_ptr tmp(std::move(other));
            swap(*this, tmp);
            return *this;
        }

        // swap is straightforward too
        friend void swap(deep_copy_ptr& a, deep_copy_ptr& b) noexcept
        {
            using std::swap;
            swap(static_cast<allocator_ref&>(a), static_cast<allocator_ref&>(b));
            swap(a.ptr_, b.ptr_);
        }

        explicit operator bool() const
        {
            return !!ptr_;
        }

        T& operator*()
        {
            return *ptr_;
        }

        const T& operator*() const
        {
            return *ptr_;
        }

        T* operator->()
        {
            return ptr_;
        }

        const T* operator->() const
        {
            return ptr_;
        }

    private:
        template <typename... Args>
        T* create(Args&&... args)
        {
            auto storage =
                this->allocate_node(sizeof(T), alignof(T)); // first allocate storage for the node
            try
            {
                ::new (storage) T(std::forward<Args>(args)...); // then call constructor
            }
            catch (...)
            {
                this->deallocate_node(storage, sizeof(T),
                                      alignof(T)); // if failure, deallocate storage again
                throw;
            }
            return static_cast<T*>(storage);
        }

        void destroy() noexcept
        {
            if (ptr_)
            {
                ptr_->~T();                                         // call destructor
                this->deallocate_node(ptr_, sizeof(T), alignof(T)); // deallocate storage
            }
        }

        T* ptr_;
    };
}

// simple usage functions

template <class Ptr>
void use_ptr()
{
    Ptr a(4), b(3);
    std::cout << *a << ' ' << *b << '\n';
    swap(a, b);

    auto c = a;
    std::cout << *a << ' ' << *c << '\n';

    auto d = std::move(b);
    std::cout << std::boolalpha << *d << ' ' << !!b << '\n';
}

int main()
{
    std::cout << "Allocator\n\n";
    use_ptr<using_std_allocator::deep_copy_ptr<int>>();
    std::cout << "\n\nRawAllocator\n\n";
    use_ptr<using_raw_allocator::deep_copy_ptr<int>>();
}