Connecting Tech Pros Worldwide Forums | Help | Site Map

why is ostream::tellp not const?

Sandor
Guest
 
Posts: n/a
#1: Jul 23 '05
Hi,

I have an application where I want to check if the buffer of a given
ostream contains any characters or it is empty. The same ostream may be
checked from multiple threads. Thread safety is guaranteed by having
only const-access in every thread to the ostream. I believe that STL
streams, just like STL containers are thread-safe if you only do const
operations on them. But it turned out that the tellp method of ostream
is defined as non-const by the standard. The standard defines tellp as:

if fail() != false, returns pos_type(1) to indicate failure.
Otherwise, returns rdbuf()->*pubseekoff(0, cur, out).

Clearly neither of these need write access to the ostream itself. This
can be proven by calling the fail(), rdbuf() and pubseekoff() methods
from client code through a const ostream reference. The trick in this is
that rdbuf() is a const method of ostream returning a non-const pointer
to the buffer. Through this non-const buffer pointer the client code can
call the pubseekoff method directly.

int client_code_tellp(const ostream &o)
{
if(o.fail()) return pos_type(1);
else return o.rdbuf()->pubseekoff(0, cur, out);
}

Now the possibility of this from client code suggests that the C++
standard is buggy in not declaring the tellp method itself const.

Another idea I am having: is this client_code_tellp threadsafe? Can it
be called from multiple threads on the same ostream? If the pubseekoff
is a non-const method then it can write to any member of the buffer,
which would be catastrophic for multithreading. Logically it should not,
if I am seeking 0 elements, but it has the possibility. Is there any
guarantee for this? It would be much cleaner if the buffer would provide
a separate const tellp method itself, instead of having to use a
non-const method just to get out some information.

Can somebody provide some insight?

- Sandor

Closed Thread