diff --git a/esphome/components/json/json_util.cpp b/esphome/components/json/json_util.cpp index 40a3496981..e03f95fe7c 100644 --- a/esphome/components/json/json_util.cpp +++ b/esphome/components/json/json_util.cpp @@ -31,6 +31,7 @@ struct SpiRamAllocator : ArduinoJson::Allocator { protected: RAMAllocator allocator_{RAMAllocator(RAMAllocator::NONE)}; }; + #endif std::string build_json(const json_build_t &f) { @@ -73,22 +74,14 @@ bool parse_json(const std::string &data, const json_parse_t &f) { JsonBuilder::JsonBuilder() : doc_( #ifdef USE_PSRAM - [this]() { - auto *alloc = new SpiRamAllocator(); // NOLINT(cppcoreguidelines-owning-memory) - allocator_ = alloc; - return alloc; - }() + (allocator_ = std::make_unique(), allocator_.get()) #else nullptr #endif ) { } -JsonBuilder::~JsonBuilder() { -#ifdef USE_PSRAM - delete static_cast(allocator_); // NOLINT(cppcoreguidelines-owning-memory) -#endif -} +JsonBuilder::~JsonBuilder() = default; std::string JsonBuilder::serialize() { if (doc_.overflowed()) { diff --git a/esphome/components/json/json_util.h b/esphome/components/json/json_util.h index 8eac87b10a..633e8182fb 100644 --- a/esphome/components/json/json_util.h +++ b/esphome/components/json/json_util.h @@ -25,6 +25,9 @@ std::string build_json(const json_build_t &f); /// Parse a JSON string and run the provided json parse function if it's valid. bool parse_json(const std::string &data, const json_parse_t &f); +// Forward declaration to avoid exposing implementation details +struct SpiRamAllocator; + /// Builder class for creating JSON documents without lambdas class JsonBuilder { public: @@ -42,13 +45,12 @@ class JsonBuilder { std::string serialize(); private: +#ifdef USE_PSRAM + std::unique_ptr allocator_; // One heap allocation, but keeps code clean +#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