use unique_ptr to avoid manual deletion

This commit is contained in:
Nicu Hodos 2025-10-11 14:27:58 +02:00
parent 12663901ab
commit fd40969c20

View File

@ -97,14 +97,12 @@ namespace Ha {
serializeJson(jsonDoc, message); serializeJson(jsonDoc, message);
auto configTopic = buildConfigTopic(); auto configTopic = buildConfigTopic();
publisher(configTopic, message); publisher(configTopic.get(), message);
delete configTopic;
} }
void publishCleanupConfig() { void publishCleanupConfig() {
auto configTopic = buildConfigTopic(); auto configTopic = buildConfigTopic();
publisher(configTopic, ""); publisher(configTopic.get(), "");
delete configTopic;
} }
void toJson(JsonDocument& jsonDoc) { void toJson(JsonDocument& jsonDoc) {
@ -135,14 +133,14 @@ namespace Ha {
jsonDoc["unique_id"] = uniqueId; jsonDoc["unique_id"] = uniqueId;
} }
const char* buildConfigTopic() { unique_ptr<char[]> buildConfigTopic() {
char* configTopic = new char[TOPIC_SIZE]; unique_ptr<char[]> topic(new char[TOPIC_SIZE]);
if (multiValueComponent && deviceClass) { 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 { } 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) { Command(Component* cmp, onMessage f) : f(f), cmp(cmp) {
auto commandTopic = buildTopic(); auto commandTopic = buildTopic();
mapCommandTopics.insert({ string(commandTopic), this }); mapCommandTopics.insert({ string(commandTopic.get()), this });
mapCommandIds.insert({ string(cmp->id), this }); mapCommandIds.insert({ string(cmp->id), this });
delete commandTopic;
} }
virtual void onCommand(const char* msg) { virtual void onCommand(const char* msg) {
@ -171,17 +168,16 @@ namespace Ha {
void buildConfig(JsonDocument& jsonDoc) override { void buildConfig(JsonDocument& jsonDoc) override {
auto commandTopic = buildTopic(); auto commandTopic = buildTopic();
jsonDoc["command_topic"] = commandTopic; jsonDoc["command_topic"] = commandTopic.get();
delete commandTopic;
if (retain) jsonDoc["retain"] = true; if (retain) jsonDoc["retain"] = true;
} }
private: private:
Component* cmp; Component* cmp;
char* buildTopic() { unique_ptr<char[]> buildTopic() {
char* commandTopic = new char[TOPIC_SIZE]; unique_ptr<char[]> topic(new char[TOPIC_SIZE]);
snprintf(commandTopic, TOPIC_SIZE, BASE_TOPIC"/set", cmp->id); snprintf(topic.get(), TOPIC_SIZE, BASE_TOPIC "/set", cmp->id);
return commandTopic; return topic;
} }
}; };