Skip to content

Commit 342248f

Browse files
committed
fix: control array and element life cycle
1 parent 46c945d commit 342248f

1 file changed

Lines changed: 17 additions & 6 deletions

File tree

tuple/include/array_tuple_sketch.hpp

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,27 +34,38 @@ class array {
3434
public:
3535
using value_type = T;
3636
using allocator_type = Allocator;
37+
using alloc_traits = std::allocator_traits<Allocator>;
3738

38-
explicit array(uint8_t size, T value, const Allocator& allocator = Allocator()):
39-
allocator_(allocator), size_(size), array_(allocator_.allocate(size_)) {
40-
std::fill(array_, array_ + size_, value);
39+
explicit array(uint8_t size, const T& value, const Allocator& allocator = Allocator()):
40+
allocator_(allocator), size_(size), array_(size_ == 0 ? nullptr : allocator_.allocate(size_)) {
41+
for (uint8_t i = 0; i < size_; ++i) {
42+
alloc_traits::construct(allocator_, array_ + i, value);
43+
}
4144
}
4245
array(const array& other):
4346
allocator_(other.allocator_),
4447
size_(other.size_),
45-
array_(allocator_.allocate(size_))
48+
array_(size_ == 0 ? nullptr : allocator_.allocate(size_))
4649
{
47-
std::copy(other.array_, other.array_ + size_, array_);
50+
for (uint8_t i = 0; i < size_; ++i) {
51+
alloc_traits::construct(allocator_, array_ + i, other.array_[i]);
52+
}
4853
}
4954
array(array&& other) noexcept:
5055
allocator_(std::move(other.allocator_)),
5156
size_(other.size_),
5257
array_(other.array_)
5358
{
5459
other.array_ = nullptr;
60+
other.size_ = 0;
5561
}
5662
~array() {
57-
if (array_ != nullptr) allocator_.deallocate(array_, size_);
63+
if (array_ != nullptr) {
64+
for (uint8_t i = 0; i < size_; ++i) {
65+
alloc_traits::destroy(allocator_, array_ + i);
66+
}
67+
allocator_.deallocate(array_, size_);
68+
}
5869
}
5970
array& operator=(const array& other) {
6071
array copy(other);

0 commit comments

Comments
 (0)