File: joint_allocator.hpp

package info (click to toggle)
foonathan-memory 0.7.4-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,644 kB
  • sloc: cpp: 12,425; xml: 139; sh: 48; makefile: 25
file content (926 lines) | stat: -rw-r--r-- 34,485 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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
// Copyright (C) 2015-2025 Jonathan Müller and foonathan/memory contributors
// SPDX-License-Identifier: Zlib

#ifndef FOONATHAN_MEMORY_JOINT_ALLOCATOR_HPP_INCLUDED
#define FOONATHAN_MEMORY_JOINT_ALLOCATOR_HPP_INCLUDED

/// \file
/// Class template \ref foonathan::memory::joint_ptr, \ref foonathan::memory::joint_allocator and related.

#include <initializer_list>
#include <new>

#include "detail/align.hpp"
#include "detail/memory_stack.hpp"
#include "detail/utility.hpp"
#include "allocator_storage.hpp"
#include "config.hpp"
#include "default_allocator.hpp"
#include "error.hpp"

namespace foonathan
{
    namespace memory
    {
        template <typename T, class RawAllocator>
        class joint_ptr;

        template <typename T>
        class joint_type;

        namespace detail
        {
            // the stack that allocates the joint memory
            class joint_stack
            {
            public:
                joint_stack(void* mem, std::size_t cap) noexcept
                : stack_(static_cast<char*>(mem)), end_(static_cast<char*>(mem) + cap)
                {
                }

                void* allocate(std::size_t size, std::size_t alignment) noexcept
                {
                    return stack_.allocate(end_, size, alignment, 0u);
                }

                bool bump(std::size_t offset) noexcept
                {
                    if (offset > std::size_t(end_ - stack_.top()))
                        return false;
                    stack_.bump(offset);
                    return true;
                }

                char* top() noexcept
                {
                    return stack_.top();
                }

                const char* top() const noexcept
                {
                    return stack_.top();
                }

                void unwind(void* ptr) noexcept
                {
                    stack_.unwind(static_cast<char*>(ptr));
                }

                std::size_t capacity(const char* mem) const noexcept
                {
                    return std::size_t(end_ - mem);
                }

                std::size_t capacity_left() const noexcept
                {
                    return std::size_t(end_ - top());
                }

                std::size_t capacity_used(const char* mem) const noexcept
                {
                    return std::size_t(top() - mem);
                }

            private:
                detail::fixed_memory_stack stack_;
                char*                      end_;
            };

            template <typename T>
            detail::joint_stack& get_stack(joint_type<T>& obj) noexcept;

            template <typename T>
            const detail::joint_stack& get_stack(const joint_type<T>& obj) noexcept;
        } // namespace detail

        /// Tag type that can't be created.
        ///
        /// It isued by \ref joint_ptr.
        /// \ingroup allocator
        class joint
        {
            joint(std::size_t cap) noexcept : capacity(cap) {}

            std::size_t capacity;

            template <typename T, class RawAllocator>
            friend class joint_ptr;
            template <typename T>
            friend class joint_type;
        };

        /// Tag type to make the joint size more explicit.
        ///
        /// It is used by \ref joint_ptr.
        /// \ingroup allocator
        struct joint_size
        {
            std::size_t size;

            explicit joint_size(std::size_t s) noexcept : size(s) {}
        };

        /// CRTP base class for all objects that want to use joint memory.
        ///
        /// This will disable default copy/move operations
        /// and inserts additional members for the joint memory management.
        /// \ingroup allocator
        template <typename T>
        class joint_type
        {
        protected:
            /// \effects Creates the base class,
            /// the tag type cannot be created by the user.
            /// \note This ensures that you cannot create joint types yourself.
            joint_type(joint j) noexcept;

            joint_type(const joint_type&) = delete;
            joint_type(joint_type&&)      = delete;

        private:
            detail::joint_stack stack_;

            template <typename U>
            friend detail::joint_stack& detail::get_stack(joint_type<U>& obj) noexcept;
            template <typename U>
            friend const detail::joint_stack& detail::get_stack(const joint_type<U>& obj) noexcept;
        };

        namespace detail
        {
            template <typename T>
            detail::joint_stack& get_stack(joint_type<T>& obj) noexcept
            {
                return obj.stack_;
            }

            template <typename T>
            const detail::joint_stack& get_stack(const joint_type<T>& obj) noexcept
            {
                return obj.stack_;
            }

            template <typename T>
            char* get_memory(joint_type<T>& obj) noexcept
            {
                auto mem = static_cast<void*>(&obj);
                return static_cast<char*>(mem) + sizeof(T);
            }

            template <typename T>
            const char* get_memory(const joint_type<T>& obj) noexcept
            {
                auto mem = static_cast<const void*>(&obj);
                return static_cast<const char*>(mem) + sizeof(T);
            }

        } // namespace detail

        template <typename T>
        joint_type<T>::joint_type(joint j) noexcept : stack_(detail::get_memory(*this), j.capacity)
        {
            FOONATHAN_MEMORY_ASSERT(stack_.top() == detail::get_memory(*this));
            FOONATHAN_MEMORY_ASSERT(stack_.capacity_left() == j.capacity);
        }

        /// A pointer to an object where all allocations are joint.
        ///
        /// It can either own an object or not (be `nullptr`).
        /// When it owns an object, it points to a memory block.
        /// This memory block contains both the actual object (of the type `T`)
        /// and space for allocations of `T`s members.
        ///
        /// The type `T` must be derived from \ref joint_type and every constructor must take \ref joint
        /// as first parameter.
        /// This prevents that you create joint objects yourself,
        /// without the additional storage.
        /// The default copy and move constructors are also deleted,
        /// you need to write them yourself.
        ///
        /// You can only access the object through the pointer,
        /// use \ref joint_allocator or \ref joint_array as members of `T`,
        /// to enable the memory sharing.
        /// If you are using \ref joint_allocator inside STL containers,
        /// make sure that you do not call their regular copy/move constructors,
        /// but instead the version where you pass an allocator.
        ///
        /// The memory block will be managed by the given \concept{concept_rawallocator,RawAllocator},
        /// it is stored in an \ref allocator_reference and not owned by the pointer directly.
        /// \ingroup allocator
        template <typename T, class RawAllocator>
        class joint_ptr : FOONATHAN_EBO(allocator_reference<RawAllocator>)
        {
            static_assert(std::is_base_of<joint_type<T>, T>::value,
                          "T must be derived of joint_type<T>");

        public:
            using element_type   = T;
            using allocator_type = typename allocator_reference<RawAllocator>::allocator_type;

            //=== constructors/destructor/assignment ===//
            /// @{
            /// \effects Creates it with a \concept{concept_rawallocator,RawAllocator}, but does not own a new object.
            explicit joint_ptr(allocator_type& alloc) noexcept
            : allocator_reference<RawAllocator>(alloc), ptr_(nullptr)
            {
            }

            explicit joint_ptr(const allocator_type& alloc) noexcept
            : allocator_reference<RawAllocator>(alloc), ptr_(nullptr)
            {
            }
            /// @}

            /// @{
            /// \effects Reserves memory for the object and the additional size,
            /// and creates the object by forwarding the arguments to its constructor.
            /// The \concept{concept_rawallocator,RawAllocator} will be used for the allocation.
            template <typename... Args>
            joint_ptr(allocator_type& alloc, joint_size additional_size, Args&&... args)
            : joint_ptr(alloc)
            {
                create(additional_size.size, detail::forward<Args>(args)...);
            }

            template <typename... Args>
            joint_ptr(const allocator_type& alloc, joint_size additional_size, Args&&... args)
            : joint_ptr(alloc)
            {
                create(additional_size.size, detail::forward<Args>(args)...);
            }
            /// @}

            /// \effects Move-constructs the pointer.
            /// Ownership will be transferred from `other` to the new object.
            joint_ptr(joint_ptr&& other) noexcept
            : allocator_reference<RawAllocator>(detail::move(other)), ptr_(other.ptr_)
            {
                other.ptr_ = nullptr;
            }

            /// \effects Destroys the object and deallocates its storage.
            ~joint_ptr() noexcept
            {
                reset();
            }

            /// \effects Move-assings the pointer.
            /// The previously owned object will be destroyed,
            /// and ownership of `other` transferred.
            joint_ptr& operator=(joint_ptr&& other) noexcept
            {
                joint_ptr tmp(detail::move(other));
                swap(*this, tmp);
                return *this;
            }

            /// \effects Same as `reset()`.
            joint_ptr& operator=(std::nullptr_t) noexcept
            {
                reset();
                return *this;
            }

            /// \effects Swaps to pointers and their ownership and allocator.
            friend void swap(joint_ptr& a, joint_ptr& b) noexcept
            {
                detail::adl_swap(static_cast<allocator_reference<RawAllocator>&>(a),
                                 static_cast<allocator_reference<RawAllocator>&>(b));
                detail::adl_swap(a.ptr_, b.ptr_);
            }

            //=== modifiers ===//
            /// \effects Destroys the object it refers to,
            /// if there is any.
            void reset() noexcept
            {
                if (ptr_)
                {
                    (**this).~element_type();
                    this->deallocate_node(ptr_,
                                          sizeof(element_type)
                                              + detail::get_stack(*ptr_).capacity(
                                                  detail::get_memory(*ptr_)),
                                          alignof(element_type));
                    ptr_ = nullptr;
                }
            }

            //=== accessors ===//
            /// \returns `true` if the pointer does own an object,
            /// `false` otherwise.
            explicit operator bool() const noexcept
            {
                return ptr_ != nullptr;
            }

            /// \returns A reference to the object it owns.
            /// \requires The pointer must own an object,
            /// i.e. `operator bool()` must return `true`.
            element_type& operator*() const noexcept
            {
                FOONATHAN_MEMORY_ASSERT(ptr_);
                return *get();
            }

            /// \returns A pointer to the object it owns.
            /// \requires The pointer must own an object,
            /// i.e. `operator bool()` must return `true`.
            element_type* operator->() const noexcept
            {
                FOONATHAN_MEMORY_ASSERT(ptr_);
                return get();
            }

            /// \returns A pointer to the object it owns
            /// or `nullptr`, if it does not own any object.
            element_type* get() const noexcept
            {
                return static_cast<element_type*>(ptr_);
            }

            /// \returns A reference to the allocator it will use for the deallocation.
            auto get_allocator() const noexcept
                -> decltype(std::declval<allocator_reference<allocator_type>>().get_allocator())
            {
                return this->allocator_reference<allocator_type>::get_allocator();
            }

        private:
            template <typename... Args>
            void create(std::size_t additional_size, Args&&... args)
            {
                auto mem = this->allocate_node(sizeof(element_type) + additional_size,
                                               alignof(element_type));

                element_type* ptr = nullptr;
#if FOONATHAN_HAS_EXCEPTION_SUPPORT
                try
                {
                    ptr = ::new (mem)
                        element_type(joint(additional_size), detail::forward<Args>(args)...);
                }
                catch (...)
                {
                    this->deallocate_node(mem, sizeof(element_type) + additional_size,
                                          alignof(element_type));
                    throw;
                }
#else
                ptr = ::new (mem)
                    element_type(joint(additional_size), detail::forward<Args>(args)...);
#endif
                ptr_ = ptr;
            }

            joint_type<T>* ptr_;

            friend class joint_allocator;
        };

        /// @{
        /// \returns `!ptr`,
        /// i.e. if `ptr` does not own anything.
        /// \relates joint_ptr
        template <typename T, class RawAllocator>
        bool operator==(const joint_ptr<T, RawAllocator>& ptr, std::nullptr_t)
        {
            return !ptr;
        }

        template <typename T, class RawAllocator>
        bool operator==(std::nullptr_t, const joint_ptr<T, RawAllocator>& ptr)
        {
            return ptr == nullptr;
        }
        /// @}

        /// @{
        /// \returns `ptr.get() == p`,
        /// i.e. if `ptr` ownws the object referred to by `p`.
        /// \relates joint_ptr
        template <typename T, class RawAllocator>
        bool operator==(const joint_ptr<T, RawAllocator>& ptr, T* p)
        {
            return ptr.get() == p;
        }

        template <typename T, class RawAllocator>
        bool operator==(T* p, const joint_ptr<T, RawAllocator>& ptr)
        {
            return ptr == p;
        }
        /// @}

        /// @{
        /// \returns `!(ptr == nullptr)`,
        /// i.e. if `ptr` does own something.
        /// \relates joint_ptr
        template <typename T, class RawAllocator>
        bool operator!=(const joint_ptr<T, RawAllocator>& ptr, std::nullptr_t)
        {
            return !(ptr == nullptr);
        }

        template <typename T, class RawAllocator>
        bool operator!=(std::nullptr_t, const joint_ptr<T, RawAllocator>& ptr)
        {
            return ptr != nullptr;
        }
        /// @}

        /// @{
        /// \returns `!(ptr == p)`,
        /// i.e. if `ptr` does not ownw the object referred to by `p`.
        /// \relates joint_ptr
        template <typename T, class RawAllocator>
        bool operator!=(const joint_ptr<T, RawAllocator>& ptr, T* p)
        {
            return !(ptr == p);
        }

        template <typename T, class RawAllocator>
        bool operator!=(T* p, const joint_ptr<T, RawAllocator>& ptr)
        {
            return ptr != p;
        }
        /// @}

        /// @{
        /// \returns A new \ref joint_ptr as if created with the same arguments passed to the constructor.
        /// \relatesalso joint_ptr
        /// \ingroup allocator
        template <typename T, class RawAllocator, typename... Args>
        auto allocate_joint(RawAllocator& alloc, joint_size additional_size, Args&&... args)
            -> joint_ptr<T, RawAllocator>
        {
            return joint_ptr<T, RawAllocator>(alloc, additional_size,
                                              detail::forward<Args>(args)...);
        }

        template <typename T, class RawAllocator, typename... Args>
        auto allocate_joint(const RawAllocator& alloc, joint_size additional_size, Args&&... args)
            -> joint_ptr<T, RawAllocator>
        {
            return joint_ptr<T, RawAllocator>(alloc, additional_size,
                                              detail::forward<Args>(args)...);
        }
        /// @}

        /// @{
        /// \returns A new \ref joint_ptr that points to a copy of `joint`.
        /// It will allocate as much memory as needed and forward to the copy constructor.
        /// \ingroup allocator
        template <class RawAllocator, typename T>
        auto clone_joint(RawAllocator& alloc, const joint_type<T>& joint)
            -> joint_ptr<T, RawAllocator>
        {
            return joint_ptr<T, RawAllocator>(alloc,
                                              joint_size(detail::get_stack(joint).capacity_used(
                                                  detail::get_memory(joint))),
                                              static_cast<const T&>(joint));
        }

        template <class RawAllocator, typename T>
        auto clone_joint(const RawAllocator& alloc, const joint_type<T>& joint)
            -> joint_ptr<T, RawAllocator>
        {
            return joint_ptr<T, RawAllocator>(alloc,
                                              joint_size(detail::get_stack(joint).capacity_used(
                                                  detail::get_memory(joint))),
                                              static_cast<const T&>(joint));
        }
        /// @}

        /// A \concept{concept_rawallocator,RawAllocator} that uses the additional joint memory for its allocation.
        ///
        /// It is somewhat limited and allows only allocation once.
        /// All joint allocators for an object share the joint memory and must not be used in multiple threads.
        /// The memory it returns is owned by a \ref joint_ptr and will be destroyed through it.
        /// \ingroup allocator
        class joint_allocator
        {
        public:
#if defined(__GNUC__) && (!defined(_GLIBCXX_USE_CXX11_ABI) || _GLIBCXX_USE_CXX11_ABI == 0)
            // std::string requires default constructor for the small string optimization when using gcc's old ABI
            // so add one, but it must never be used for allocation
            joint_allocator() noexcept : stack_(nullptr) {}
#endif

            /// \effects Creates it using the joint memory of the given object.
            template <typename T>
            joint_allocator(joint_type<T>& j) noexcept : stack_(&detail::get_stack(j))
            {
            }

            joint_allocator(const joint_allocator& other) noexcept            = default;
            joint_allocator& operator=(const joint_allocator& other) noexcept = default;

            /// \effects Allocates a node with given properties.
            /// \returns A pointer to the new node.
            /// \throws \ref out_of_fixed_memory exception if this function has been called for a second time
            /// or the joint memory block is exhausted.
            void* allocate_node(std::size_t size, std::size_t alignment)
            {
                FOONATHAN_MEMORY_ASSERT(stack_);
                auto mem = stack_->allocate(size, alignment);
                if (!mem)
                    FOONATHAN_THROW(out_of_fixed_memory(info(), size));
                return mem;
            }

            /// \effects Deallocates the node, if possible.
            /// \note It is only possible if it was the last allocation.
            void deallocate_node(void* ptr, std::size_t size, std::size_t) noexcept
            {
                FOONATHAN_MEMORY_ASSERT(stack_);
                auto end = static_cast<char*>(ptr) + size;
                if (end == stack_->top())
                    stack_->unwind(ptr);
            }

        private:
            allocator_info info() const noexcept
            {
                return allocator_info(FOONATHAN_MEMORY_LOG_PREFIX "::joint_allocator", this);
            }

            detail::joint_stack* stack_;

            friend bool operator==(const joint_allocator& lhs, const joint_allocator& rhs) noexcept;
        };

        /// @{
        /// \returns Whether `lhs` and `rhs` use the same joint memory for the allocation.
        /// \relates joint_allocator
        inline bool operator==(const joint_allocator& lhs, const joint_allocator& rhs) noexcept
        {
            return lhs.stack_ == rhs.stack_;
        }

        inline bool operator!=(const joint_allocator& lhs, const joint_allocator& rhs) noexcept
        {
            return !(lhs == rhs);
        }
        /// @}

        /// Specialization of \ref is_shared_allocator to mark \ref joint_allocator as shared.
        /// This allows using it as \ref allocator_reference directly.
        /// \ingroup allocator
        template <>
        struct is_shared_allocator<joint_allocator> : std::true_type
        {
        };

        /// Specialization of \ref is_thread_safe_allocator to mark \ref joint_allocator as thread safe.
        /// This is an optimization to get rid of the mutex in \ref allocator_storage,
        /// as joint allocator must not be shared between threads.
        /// \note The allocator is *not* thread safe, it just must not be shared.
        template <>
        struct is_thread_safe_allocator<joint_allocator> : std::true_type
        {
        };

#if !defined(DOXYGEN)
        template <class RawAllocator>
        struct propagation_traits;
#endif

        /// Specialization of the \ref propagation_traits for the \ref joint_allocator.
        /// A joint allocator does not propagate on assignment
        /// and it is not allowed to use the regular copy/move constructor of allocator aware containers,
        /// instead it needs the copy/move constructor with allocator.
        /// \note This is required because the container constructor will end up copying/moving the allocator.
        /// But this is not allowed as you need the allocator with the correct joined memory.
        /// Copying can be customized (i.e. forbidden), but sadly not move, so keep that in mind.
        /// \ingroup allocator
        template <>
        struct propagation_traits<joint_allocator>
        {
            using propagate_on_container_swap            = std::false_type;
            using propagate_on_container_move_assignment = std::false_type;
            using propagate_on_container_copy_assignment = std::false_type;

            template <class AllocReference>
            static AllocReference select_on_container_copy_construction(const AllocReference&)
            {
                static_assert(always_false<AllocReference>::value,
                              "you must not use the regular copy constructor");
            }

        private:
            template <typename T>
            struct always_false : std::false_type
            {
            };
        };

        /// A zero overhead dynamic array using joint memory.
        ///
        /// If you use, e.g. `std::vector` with \ref joint_allocator,
        /// this has a slight additional overhead.
        /// This type is joint memory aware and has no overhead.
        ///
        /// It has a dynamic, but fixed size,
        /// it cannot grow after it has been created.
        /// \ingroup allocator
        template <typename T>
        class joint_array
        {
        public:
            using value_type     = T;
            using iterator       = value_type*;
            using const_iterator = const value_type*;

            //=== constructors ===//
            /// \effects Creates with `size` default-constructed objects using the specified joint memory.
            /// \throws \ref out_of_fixed_memory if `size` is too big
            /// and anything thrown by `T`s constructor.
            /// If an allocation is thrown, the memory will be released directly.
            template <typename JointType>
            joint_array(std::size_t size, joint_type<JointType>& j)
            : joint_array(detail::get_stack(j), size)
            {
            }

            /// \effects Creates with `size` copies of `val`  using the specified joint memory.
            /// \throws \ref out_of_fixed_memory if `size` is too big
            /// and anything thrown by `T`s constructor.
            /// If an allocation is thrown, the memory will be released directly.
            template <typename JointType>
            joint_array(std::size_t size, const value_type& val, joint_type<JointType>& j)
            : joint_array(detail::get_stack(j), size, val)
            {
            }

            /// \effects Creates with the copies of the objects in the initializer list using the specified joint memory.
            /// \throws \ref out_of_fixed_memory if the size is too big
            /// and anything thrown by `T`s constructor.
            /// If an allocation is thrown, the memory will be released directly.
            template <typename JointType>
            joint_array(std::initializer_list<value_type> ilist, joint_type<JointType>& j)
            : joint_array(detail::get_stack(j), ilist)
            {
            }

            /// \effects Creates it by forwarding each element of the range to `T`s constructor  using the specified joint memory.
            /// \throws \ref out_of_fixed_memory if the size is too big
            /// and anything thrown by `T`s constructor.
            /// If an allocation is thrown, the memory will be released directly.
            template <typename InIter, typename JointType,
                      typename = decltype(*std::declval<InIter&>()++)>
            joint_array(InIter begin, InIter end, joint_type<JointType>& j)
            : joint_array(detail::get_stack(j), begin, end)
            {
            }

            joint_array(const joint_array&) = delete;

            /// \effects Copy constructs each element from `other` into the storage of the specified joint memory.
            /// \throws \ref out_of_fixed_memory if the size is too big
            /// and anything thrown by `T`s constructor.
            /// If an allocation is thrown, the memory will be released directly.
            template <typename JointType>
            joint_array(const joint_array& other, joint_type<JointType>& j)
            : joint_array(detail::get_stack(j), other)
            {
            }

            joint_array(joint_array&&) = delete;

            /// \effects Move constructs each element from `other` into the storage of the specified joint memory.
            /// \throws \ref out_of_fixed_memory if the size is too big
            /// and anything thrown by `T`s constructor.
            /// If an allocation is thrown, the memory will be released directly.
            template <typename JointType>
            joint_array(joint_array&& other, joint_type<JointType>& j)
            : joint_array(detail::get_stack(j), detail::move(other))
            {
            }

            /// \effects Destroys all objects,
            /// but does not release the storage.
            ~joint_array() noexcept
            {
                for (std::size_t i = 0u; i != size_; ++i)
                    ptr_[i].~T();
            }

            joint_array& operator=(const joint_array&) = delete;
            joint_array& operator=(joint_array&&)      = delete;

            //=== accessors ===//
            /// @{
            /// \returns A reference to the `i`th object.
            /// \requires `i < size()`.
            value_type& operator[](std::size_t i) noexcept
            {
                FOONATHAN_MEMORY_ASSERT(i < size_);
                return ptr_[i];
            }

            const value_type& operator[](std::size_t i) const noexcept
            {
                FOONATHAN_MEMORY_ASSERT(i < size_);
                return ptr_[i];
            }
            /// @}

            /// @{
            /// \returns A pointer to the first object.
            /// It points to contiguous memory and can be used to access the objects directly.
            value_type* data() noexcept
            {
                return ptr_;
            }

            const value_type* data() const noexcept
            {
                return ptr_;
            }
            /// @}

            /// @{
            /// \returns A random access iterator to the first element.
            iterator begin() noexcept
            {
                return ptr_;
            }

            const_iterator begin() const noexcept
            {
                return ptr_;
            }
            /// @}

            /// @{
            /// \returns A random access iterator one past the last element.
            iterator end() noexcept
            {
                return ptr_ + size_;
            }

            const_iterator end() const noexcept
            {
                return ptr_ + size_;
            }
            /// @}

            /// \returns The number of elements in the array.
            std::size_t size() const noexcept
            {
                return size_;
            }

            /// \returns `true` if the array is empty, `false` otherwise.
            bool empty() const noexcept
            {
                return size_ == 0u;
            }

        private:
            // allocate only
            struct allocate_only
            {
            };
            joint_array(allocate_only, detail::joint_stack& stack, std::size_t size)
            : ptr_(nullptr), size_(0u)
            {
                ptr_ = static_cast<T*>(stack.allocate(size * sizeof(T), alignof(T)));
                if (!ptr_)
                    FOONATHAN_THROW(out_of_fixed_memory(info(), size * sizeof(T)));
            }

            class builder
            {
            public:
                builder(detail::joint_stack& stack, T* ptr) noexcept
                : stack_(&stack), objects_(ptr), size_(0u)
                {
                }

                ~builder() noexcept
                {
                    for (std::size_t i = 0u; i != size_; ++i)
                        objects_[i].~T();

                    if (size_)
                        stack_->unwind(objects_);
                }

                builder(builder&&)            = delete;
                builder& operator=(builder&&) = delete;

                template <typename... Args>
                T* create(Args&&... args)
                {
                    auto ptr = ::new (static_cast<void*>(&objects_[size_]))
                        T(detail::forward<Args>(args)...);
                    ++size_;
                    return ptr;
                }

                std::size_t size() const noexcept
                {
                    return size_;
                }

                std::size_t release() noexcept
                {
                    auto res = size_;
                    size_    = 0u;
                    return res;
                }

            private:
                detail::joint_stack* stack_;
                T*                   objects_;
                std::size_t          size_;
            };

            joint_array(detail::joint_stack& stack, std::size_t size)
            : joint_array(allocate_only{}, stack, size)
            {
                builder b(stack, ptr_);
                for (auto i = 0u; i != size; ++i)
                    b.create();
                size_ = b.release();
            }

            joint_array(detail::joint_stack& stack, std::size_t size, const value_type& value)
            : joint_array(allocate_only{}, stack, size)
            {
                builder b(stack, ptr_);
                for (auto i = 0u; i != size; ++i)
                    b.create(value);
                size_ = b.release();
            }

            joint_array(detail::joint_stack& stack, std::initializer_list<value_type> ilist)
            : joint_array(allocate_only{}, stack, ilist.size())
            {
                builder b(stack, ptr_);
                for (auto& elem : ilist)
                    b.create(elem);
                size_ = b.release();
            }

            joint_array(detail::joint_stack& stack, const joint_array& other)
            : joint_array(allocate_only{}, stack, other.size())
            {
                builder b(stack, ptr_);
                for (auto& elem : other)
                    b.create(elem);
                size_ = b.release();
            }

            joint_array(detail::joint_stack& stack, joint_array&& other)
            : joint_array(allocate_only{}, stack, other.size())
            {
                builder b(stack, ptr_);
                for (auto& elem : other)
                    b.create(detail::move(elem));
                size_ = b.release();
            }

            template <typename InIter>
            joint_array(detail::joint_stack& stack, InIter begin, InIter end)
            : ptr_(nullptr), size_(0u)
            {
                if (begin == end)
                    return;

                ptr_ = static_cast<T*>(stack.allocate(sizeof(T), alignof(T)));
                if (!ptr_)
                    FOONATHAN_THROW(out_of_fixed_memory(info(), sizeof(T)));

                builder b(stack, ptr_);
                b.create(*begin++);

                for (auto last = ptr_; begin != end; ++begin)
                {
                    // just bump stack to get more memory
                    if (!stack.bump(sizeof(T)))
                        FOONATHAN_THROW(out_of_fixed_memory(info(), b.size() * sizeof(T)));

                    auto cur = b.create(*begin);
                    FOONATHAN_MEMORY_ASSERT(last + 1 == cur);
                    last = cur;
                }

                size_ = b.release();
            }

            allocator_info info() const noexcept
            {
                return {FOONATHAN_MEMORY_LOG_PREFIX "::joint_array", this};
            }

            value_type* ptr_;
            std::size_t size_;
        };
    } // namespace memory
} // namespace foonathan

#endif // FOONATHAN_MEMORY_JOINT_ALLOCATOR_HPP_INCLUDED