From fd40969c20de28a8ac733e3a90a24ce154427c7c Mon Sep 17 00:00:00 2001 From: Nicu Hodos Date: Sat, 11 Oct 2025 14:27:58 +0200 Subject: [PATCH] use unique_ptr to avoid manual deletion --- src/ha.h | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/src/ha.h b/src/ha.h index 4f43010..2a3b4e9 100644 --- a/src/ha.h +++ b/src/ha.h @@ -97,14 +97,12 @@ namespace Ha { serializeJson(jsonDoc, message); auto configTopic = buildConfigTopic(); - publisher(configTopic, message); - delete configTopic; + publisher(configTopic.get(), message); } void publishCleanupConfig() { auto configTopic = buildConfigTopic(); - publisher(configTopic, ""); - delete configTopic; + publisher(configTopic.get(), ""); } void toJson(JsonDocument& jsonDoc) { @@ -135,14 +133,14 @@ namespace Ha { jsonDoc["unique_id"] = uniqueId; } - const char* buildConfigTopic() { - char* configTopic = new char[TOPIC_SIZE]; + unique_ptr buildConfigTopic() { + unique_ptr topic(new char[TOPIC_SIZE]); if (multiValueComponent && deviceClass) { - snprintf(configTopic, TOPIC_SIZE, CONFIG_TOPIC"_%s""/config", type, deviceClass, id); + snprintf(topic.get(), TOPIC_SIZE, CONFIG_TOPIC"_%s""/config", type, deviceClass, id); } else { - snprintf(configTopic, TOPIC_SIZE, CONFIG_TOPIC"/config", type, id); + snprintf(topic.get(), TOPIC_SIZE, CONFIG_TOPIC"/config", type, id); } - return configTopic; + return topic; } }; @@ -153,9 +151,8 @@ namespace Ha { Command(Component* cmp, onMessage f) : f(f), cmp(cmp) { auto commandTopic = buildTopic(); - mapCommandTopics.insert({ string(commandTopic), this }); + mapCommandTopics.insert({ string(commandTopic.get()), this }); mapCommandIds.insert({ string(cmp->id), this }); - delete commandTopic; } virtual void onCommand(const char* msg) { @@ -171,17 +168,16 @@ namespace Ha { void buildConfig(JsonDocument& jsonDoc) override { auto commandTopic = buildTopic(); - jsonDoc["command_topic"] = commandTopic; - delete commandTopic; + jsonDoc["command_topic"] = commandTopic.get(); if (retain) jsonDoc["retain"] = true; } private: Component* cmp; - char* buildTopic() { - char* commandTopic = new char[TOPIC_SIZE]; - snprintf(commandTopic, TOPIC_SIZE, BASE_TOPIC"/set", cmp->id); - return commandTopic; + unique_ptr buildTopic() { + unique_ptr topic(new char[TOPIC_SIZE]); + snprintf(topic.get(), TOPIC_SIZE, BASE_TOPIC "/set", cmp->id); + return topic; } };