Skip to content

Commit be79322

Browse files
committed
fix(containers): support Vector without allocator - use global new/delete
- Destructor: handle null allocator with global delete - reserve(): use global ::operator new when m_allocator is null - Move assignment: handle null allocator with global delete This fixes the segfault when using Vector without passing an allocator.
1 parent f78952f commit be79322

1 file changed

Lines changed: 24 additions & 8 deletions

File tree

src/containers/Vector.hpp

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,12 @@ class Vector {
2424
}
2525

2626
~Vector() {
27-
if (m_data && m_ownsData && m_allocator) {
28-
m_allocator->free(m_data);
27+
if (m_data && m_ownsData) {
28+
if (m_allocator) {
29+
m_allocator->free(m_data);
30+
} else {
31+
::operator delete(m_data);
32+
}
2933
}
3034
}
3135

@@ -64,8 +68,12 @@ class Vector {
6468

6569
Vector& operator=(Vector&& other) noexcept {
6670
if (this != &other) {
67-
if (m_ownsData && m_data && m_allocator) {
68-
m_allocator->free(m_data);
71+
if (m_ownsData && m_data) {
72+
if (m_allocator) {
73+
m_allocator->free(m_data);
74+
} else {
75+
::operator delete(m_data);
76+
}
6977
}
7078
m_data = other.m_data;
7179
m_size = other.m_size;
@@ -130,17 +138,25 @@ class Vector {
130138

131139
void reserve(usize newCapacity) {
132140
if (newCapacity > m_capacity) {
133-
CF_ASSERT(m_allocator, "Allocator is required for Vector");
134-
T* newData = static_cast<T*>(m_allocator->alloc(newCapacity * sizeof(T), alignof(T)));
141+
T* newData;
142+
if (m_allocator) {
143+
newData = static_cast<T*>(m_allocator->alloc(newCapacity * sizeof(T), alignof(T)));
144+
} else {
145+
newData = static_cast<T*>(::operator new(newCapacity * sizeof(T)));
146+
}
135147
CF_ASSERT_NOT_NULL(newData);
136148

137149
for (usize i = 0; i < m_size; ++i) {
138150
new (&newData[i]) T(std::move(m_data[i]));
139151
m_data[i].~T();
140152
}
141153

142-
if (m_ownsData && m_data && m_allocator) {
143-
m_allocator->free(m_data);
154+
if (m_ownsData && m_data) {
155+
if (m_allocator) {
156+
m_allocator->free(m_data);
157+
} else {
158+
::operator delete(m_data);
159+
}
144160
}
145161

146162
m_data = newData;

0 commit comments

Comments
 (0)