0

I'm trying to use libconfig library to parse variables from an external configuration file.

On libconfig site it says: The class Config represents a configuration, and the class Setting represents a configuration setting. Note that by design, neither of these classes provides a public copy constructor or assignment operator. Therefore, instances of these classes may only be passed between functions via references or pointers.

I'm having difficulty creating a function that will return a Setting class reference (From my understanding returning reference to local object is frowned upon. But I have no idea how to declare a global reference given limitation above). At the bottom I have attached snippet of my attempt at coding this, however they are not working. I'm new to C++ and currently reading a textbook on it, but I'm still shaky on my handling of reference and pointer. I would appreciate if anyone can shed some light into what I'm doing wrong.

config.cfg

A=
{
  min = 3;
}

Code

libconfig::Setting& GetKey(const char* filename, const char* method)
{
  libconfig::Config cfg;
  cfg.readFile(filename);
  libconfig::Setting &root = cfg.getRoot();
  libconfig::Setting &key = root[method];

  // How can I return key?
}

libconfig::Setting &key = GetKey("config.cfg","A");
key.lookupValue("min",min);
nasw_264
  • 97
  • 1
  • 7
  • presumably you need to keep `cfg` alive somewhere then the references will remain valid. possibly you should pass `cfg` into `GetKey` rather than opening it every time you call `GetKey`? – Alan Birtles May 28 '19 at 10:23
  • @AlanBirtles I've tried implementing your suggestion and it worked! Is that because `key` was referencing a (now) global object `cfg` and hence `key` is global as well? – nasw_264 May 28 '19 at 10:55

1 Answers1

1

The values returned from the various methods in libconfig::Config are references to objects held within the libconfig::Config object.

It isn't clear from the documentation how long these references will be valid for but they will certainly be invalid when the cfg object is destroyed. They might be invalidated if you make changes to the cfg object but that isn't stated in the documentation.

Restructuring your code to the following should work:

libconfig::Setting& GetKey(libconfig::Config& cfg, const char* method)
{
  libconfig::Setting &root = cfg.getRoot();
  libconfig::Setting &key = root[method];

  // How can I return key?
}

libconfig::Config cfg;
cfg.readFile("config.cfg");
libconfig::Setting &key = GetKey(cfg,"A");
key.lookupValue("min",min);

cfg is not not destroyed until after you stop using key so you shouldn't get dangling references.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60