Boost logo

Boost :

From: Terje Slettebø (tslettebo_at_[hidden])
Date: 2003-05-03 23:09:35


>From: "Justin M. Lewis" <boost_at_[hidden]>

> From: "Noel Yap" <Noel.Yap_at_[hidden]>
> > >From the above, it sounds like you would rather use out parameters than
> > return values. Do you write code like:
> >
> > void square_root( double input_, double& output_ );
> >
> > rather than:
> >
> > double square_root( double input_ );
>
> A little bit of an overly simple example. How about something more like
>
> void MyGetCWD(c_out<std::string> cwd)
> {
> char *buf = new char[FIRSTSIZE];
> unsigned int size = FIRSTSIZE;
> while(getcwd(buf, sizeof(buf)) == NULL)
> {
> delete [] buf;
> size += step;
> buf = new char[size];
> }
>
> cwd = buf;
> delete[] buf;
> }

std::string MyGetCWD()
{
  // ...

  return std::string(buf);
}

With a compiler implementing the Return Value Optimisation, which is a
common optimisation, this is just as efficient as the example above, and
requires no out parameter. It seems you're doing premature optimisation in
this case.

> Or, how about,
> void GetFileName(c_in_out<std::string> path, const std::string &filter)
> {
> std::string fname;
> FindFirstFileWithFilter(out(fname), path, filter);
> path += "/";
> path += fname;
> }

You can avoid the in_out parameter by simply not write a function like the
above. Avoiding in_out and out parameters also means you avoid uninitialised
variables:

std::string fname=FindFirstFileWithFilter(path, filter);

path+="/";
path+=fname;

// Use path

Note that even if a function does:

some_type f()
{
  some_type value=...;

  // ...

  return value;
}

RVO is still applicable. Compilers implementing this case includes g++ and
Intel C++.

Regards,

Terje


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk