1
0
mirror of https://github.com/esphome/esphome.git synced 2025-10-18 17:53:47 +01:00
This commit is contained in:
J. Nick Koston
2025-10-13 15:30:18 -10:00
parent 9775274007
commit 2626a851fb

View File

@@ -170,8 +170,11 @@ template<typename T> class FixedVector {
// Helper to destroy all elements without freeing memory // Helper to destroy all elements without freeing memory
void destroy_elements_() { void destroy_elements_() {
for (size_t i = 0; i < size_; i++) { // Only call destructors for non-trivially destructible types
data_[i].~T(); if constexpr (!std::is_trivially_destructible<T>::value) {
for (size_t i = 0; i < size_; i++) {
data_[i].~T();
}
} }
} }
@@ -221,7 +224,7 @@ template<typename T> class FixedVector {
reset_(); reset_();
if (n > 0) { if (n > 0) {
// Allocate raw memory without calling constructors // Allocate raw memory without calling constructors
// sizeof(T) is correct here - when T is a pointer type, we want the pointer size // sizeof(T) is correct here for any type T (value types, pointers, etc.)
// NOLINTNEXTLINE(bugprone-sizeof-expression) // NOLINTNEXTLINE(bugprone-sizeof-expression)
data_ = static_cast<T *>(::operator new(n * sizeof(T))); data_ = static_cast<T *>(::operator new(n * sizeof(T)));
capacity_ = n; capacity_ = n;
@@ -265,15 +268,11 @@ template<typename T> class FixedVector {
/// Emplace element without bounds checking - constructs in-place /// Emplace element without bounds checking - constructs in-place
/// Caller must ensure sufficient capacity was allocated via init() /// Caller must ensure sufficient capacity was allocated via init()
/// Returns reference to the newly constructed element /// Returns reference to the newly constructed element
/// Silently ignores emplaces beyond capacity (returns reference to last element) /// NOTE: Caller MUST ensure size_ < capacity_ before calling
T &emplace_back() { T &emplace_back() {
if (size_ < capacity_) { // Use placement new to default-construct the object in pre-allocated memory
// Use placement new to default-construct the object in pre-allocated memory new (&data_[size_]) T();
new (&data_[size_]) T(); size_++;
size_++;
return data_[size_ - 1];
}
// Beyond capacity - return reference to last element to avoid crash
return data_[size_ - 1]; return data_[size_ - 1];
} }