Passing struct as an argument to function with reference and assign default value for function overloading [C++]

Gaurav Arora
Gaurav Arora
Published in
2 min readSep 7, 2016

I was working on finding my way to solve a problem in a big code base. I was suppose to add a functionality.

There was an existing function stdout_to_string in xapian-application/omega

std::string stdout_to_string(const std::string &cmd, bool use_shell, int alt_status = 0);

This function internally try to run a command in linux environment and send back result to calling program. Internally on linux platform which support socketpair and fork.

  1. create socketpair which will connect child and parent process
  2. It tries to do fork.
  3. Implement execution of command in child.
  4. Read on the parent fd obtained using socketpair , read output from the child and return to the calling function.

We wanted to implement a version where we can create multiple child process and then do select on those child. So, idea was to not execute the waiting and reading from fd part in parent, rather return the fd and child pid to calling function to process them.

Since we don’t want to change signature of this function, we can’t change the return value and moreover, since this is already used at lot of places in code base, we cannot even change signature in such a way where current function call won’t work.

Above sentence basically boils down to:

  • Pass a extra argument which will store the value of fd and pid which can be read back.
  • argument needs to have a default value, so that current function calls will work as it is.
  • Should be possible to change the argument which is suppose to store the value.
  • Should be a custom structure to make it store more than 1 value.

There is elephant in the room

It is not possible to have a structure with reference value which should have default value in a sane and simple way.

Since it is structure by reference it cannot be a temporary variable . Hence we cannot do

stdout_to_string(…,ProcessData & process = ProcessData(false));

We couldn't have a global variable as its bad to do in a code base, and moreover i was getting multiple declaration

We can have NULL as a default value since NULL . As it was giving error it’s for long and cannot be assigned to struct.

After hit and trial and trying lot of thing , i finally tried using pointer and passed NULL as an default value as it’s allowed for pointer.

string
stdout_to_string(const string &cmd, bool use_shell, int alt_status, ProcessData * p_data)
{

Solution worked!!! But it’s not a good idea to use pointer if you can avoid it.

Is there a way , i can avoid using pointer in this case??

--

--

Gaurav Arora
Gaurav Arora

Currently helping build Zyft.com. Passionate about running, building stuff.