views:

19

answers:

1

I am porting some C++ code from Unix to Linux (Red Hat).

I have run into the following pattern:

ostream& myfunction(ostream& os)
{
  if (os.opfx())
  {
    os << mydata;
    os.osfx();
  }
  return os;
}

The functions opfx and osfx are not available under Red Hat 4.5. I saw a suggestion here to use the ostream::sentry functionality:

ostream& myfunction_ported(ostream& os)
{
  ostream::sentry ok(os);
  if (ok)
  {
    os << mydata;
  }
  return os;
}

I see from here that the purpose of opfx is to verify the stream state before flushing it and continuing.

My questions:

I thought the ostream functions already checked the stream state before operating on the stream. Is this true? Was this not true at some point?

Is replacing opfx with sentry necessary? What does sentry give me that operator<< doesn't give me already?

+1  A: 

Any existing inserter (unless it's really horribly buggy) is already doing to create a sentry object, so as long as your do your work via an existing inserter, you don't need to create a sentry object yourself.

You do need to create a sentry object when you write your data directly to the stream buffer on your own, without help from any existing inserter (i.e., when you're not using anything else that'll create a sentry for you).

For this code, you can just eliminate creating the sentry objects completely and do something like:

ostream& myfunction(ostream& os)
{
    return os << mydata;
}

Note that the existing code was declared to return an ostream &, but didn't seem to actually return anything.

Jerry Coffin
Thank you for the recommendation. I missed the return statement when I typed in the two samples, and have fixed it.
Bill