casacore
Loading...
Searching...
No Matches
MorphingArray.h
Go to the documentation of this file.
1#ifndef CASACORE_MORPHING_ARRAY_H_
2#define CASACORE_MORPHING_ARRAY_H_
3
4#include <cstdlib>
5#include <memory>
6#include <new>
7#include <type_traits>
8
18 public:
19 MorphingArray() noexcept = default;
20
21 template<typename T>
22 MorphingArray(size_t size) : size_(size) {
24 }
25
26 ~MorphingArray() noexcept { free(data_); }
27
28 MorphingArray(const MorphingArray&) = delete;
30
31 MorphingArray(MorphingArray&& other) noexcept : data_(other.data_), size_(other.size_) {
32 other.data_ = nullptr;
33 other.size_ = 0;
34 }
36 free(data_);
37 data_ = other.data_;
38 size_ = other.size_;
39 other.data_ = nullptr;
40 other.size_ = 0;
41 return *this;
42 }
43
48 template <typename T>
49 void Resize(size_t new_size) {
50 static_assert(std::is_trivially_destructible_v<T>);
51 if (new_size > size_) {
52 free(data_);
53 size_ = new_size;
55 }
56 }
57
58 template <typename T>
59 T* Data() {
60 static_assert(std::is_trivially_destructible_v<T>);
61 return reinterpret_cast<T*>(data_);
62 }
63
64 template <typename T>
65 const T* Data() const {
66 static_assert(std::is_trivially_destructible_v<T>);
67 return reinterpret_cast<T*>(data_);
68 }
69
70 size_t Size() const { return size_; }
71
72 private:
73 template<typename T>
74 void Allocate() {
75 if constexpr(alignof(T) > sizeof(void*)) {
76 posix_memalign(&data_, alignof(T), size_ * sizeof(T));
77 } else {
78 data_ = malloc(size_ * sizeof(T));
79 }
80 if(!data_)
81 throw std::bad_alloc();
82 std::uninitialized_default_construct_n(reinterpret_cast<T*>(data_), size_);
83 }
84
85 void* data_ = nullptr;
86 size_t size_ = 0;
87};
88
89#endif
void Resize(size_t new_size)
Make sure that the array can hold as least the specified number of elements of type T.
size_t Size() const
MorphingArray() noexcept=default
MorphingArray(const MorphingArray &)=delete
~MorphingArray() noexcept
MorphingArray & operator=(const MorphingArray &)=delete
MorphingArray(MorphingArray &&other) noexcept
const T * Data() const
MorphingArray & operator=(MorphingArray &&other) noexcept
free(pool)