Returning object reference from C++ function

516 views Asked by At

I have began learning C++ for Arduino and have run into some troubles. I have some functions reading/writing to SPIFFS files. Since the code for opening configuration files is common I would want to have a separate function to handle it.

I have come up with following function declaration

ConfigFileOpenStatus DeviceOpenConfigFile(const char *path, File *file);

The function accepts pointer to char array for the file path, and pointer to opened file. I then tried to make following function definition

ConfigFileOpenStatus DeviceOpenConfigFile(const char *path, File *file)
{
    if (SPIFFS.exists(path))
    {
        file = &SPIFFS.open(path, "r+");
        return !file ? Failed : Opened;
    }
    else
    {
        file = &SPIFFS.open(path, "w+");
        return !file ? Failed : Created;
    }
}

That did not work as compiler complained with error error: taking address of temporary [-fpermissive] As I understand this means that the file object will be disposed once DeviceOpenConfigFile function returns?

So my question is whether its possible to implement a function in a way where I can get File object reference and release it later?

1

There are 1 answers

2
Lundin On BEST ANSWER
  • SPIFFS.open apparently returns File, by value. The returned value will be a temporary variable available on that line. So taking the address of that one doesn't make any sense, for the same reason as int func (void); ... &func() doesn't make any sense. It has nothing to do with the surrounding DeviceOpenConfigFile function.
  • It doesn't make sense to assign a new address to pointer passed by parameter, for the same reason as void func (int x) { x = 0; } doesn't make sense - you change a local variable only, nothing on the caller side gets changed and nothing gets returned to the caller.

It would seem that the solution you are looking for is this:

ConfigFileOpenStatus DeviceOpenConfigFile(const char *path, File* file)
{
  ...
  *file = SPIFFS.open(path, "r+");

where file is allocated on the caller-side.