From 703bb0c9c6d0e3741e9c0603c1e131f6b275fa81 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Mon, 15 Sep 2025 21:18:52 -0500 Subject: [PATCH] cleanup --- esphome/components/json/json_util.cpp | 12 +++++++++++- esphome/components/json/json_util.h | 8 +++++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/esphome/components/json/json_util.cpp b/esphome/components/json/json_util.cpp index 6d1d258c13..40a3496981 100644 --- a/esphome/components/json/json_util.cpp +++ b/esphome/components/json/json_util.cpp @@ -73,13 +73,23 @@ bool parse_json(const std::string &data, const json_parse_t &f) { JsonBuilder::JsonBuilder() : doc_( #ifdef USE_PSRAM - (allocator_ = std::make_unique(), allocator_.get()) + [this]() { + auto *alloc = new SpiRamAllocator(); // NOLINT(cppcoreguidelines-owning-memory) + allocator_ = alloc; + return alloc; + }() #else nullptr #endif ) { } +JsonBuilder::~JsonBuilder() { +#ifdef USE_PSRAM + delete static_cast(allocator_); // NOLINT(cppcoreguidelines-owning-memory) +#endif +} + std::string JsonBuilder::serialize() { if (doc_.overflowed()) { ESP_LOGE(TAG, "JSON document overflow"); diff --git a/esphome/components/json/json_util.h b/esphome/components/json/json_util.h index 64658aa194..8eac87b10a 100644 --- a/esphome/components/json/json_util.h +++ b/esphome/components/json/json_util.h @@ -29,6 +29,7 @@ bool parse_json(const std::string &data, const json_parse_t &f); class JsonBuilder { public: JsonBuilder(); + ~JsonBuilder(); JsonObject root() { if (!root_created_) { @@ -41,12 +42,13 @@ class JsonBuilder { std::string serialize(); private: -#ifdef USE_PSRAM - std::unique_ptr allocator_; -#endif JsonDocument doc_; JsonObject root_; bool root_created_{false}; + // Allocator must be last member to ensure it's destroyed after doc_ +#ifdef USE_PSRAM + void *allocator_{nullptr}; // Will store SpiRamAllocator*, managed in cpp file +#endif }; } // namespace json