Search code examples
c++arduinoesp8266arduino-esp8266

Arduino/C++ right way to use pointers


I have the following scenario in a program that was written in C ++ (Arduino):

Service.h

class Service
{
 public:
   Service(AsyncWebServer *server, FS *fs);
   ~Service();

   void loop();

 private:
   AsyncWebServer *_server;
   FS *_fs;

   JsonObject *Settings;
   void LoadSettings();
}

Service.cpp

Service::Service(AsyncWebServer *server, FS *fs) : _server(server), _fs(fs) { }

Service::LoadSettings(){
{
  File configFile = _fs->open("data.json", "r");
  DynamicJsonBuffer jsonBuffer;
  JsonObject &root = jsonBuffer.parseObject(configFile);
  Settings = &root;
  configFile.close();
}

Service:loop() {
    LoadSettings();
}

In a correct program, once the Settings property is set, it should hold the value throughout the lifecycle, however I need to call the LoadSettings() method all the time because the Settings property is losing the value when the program exits the method LoadSettings()

What is the right way to work with pointers and class properties? What do i need to do?


Solution

  • The thing what you are doing is creating a local object by parsing the object file and then leaving the function

    DynamicJsonBuffer jsonBuffer; // declared locally
    JsonObject& root = jsonBuffer.parseObject(configFile) // root local
    

    creates root, a local reference, then you set Settings to point to address of that reference after leaving the function, jsonBuffer ceases to exist.

    You should instead either declare jsonBuffer static or better, make it a member variable _jsonBuffer

    Not sure why you need root, just write

    Settings = &(_jsonBuffer.parseObject(configFile));
    

    (maybe you should also rename Settings to _settings to have the same style as the other member variables).