I am creating my own streambuf
subclass and using the C++03 spec (ISO/IEC 14882:2003) as a reference.
In section 27.5.2.4.2 [lib.streambuf.virt.buffer], the specifications for both basic_streambuf::seekoff()
and basic_streambuf::seekpos()
say:
Default behavior: Returns pos_type(off_type(-1)).
Now, I thought off_type
was supposed to be a signed integral type and pos_type
was supposed to be an unsigned integral type, so it seems to me this expression has to be equivalent to just pos_type(-1)
.
But supposing I am mistaken, and these types mi开发者_如何学运维ght be some other combination of signed and unsigned... Then I still cannot figure out any possible use for this double cast.
For example, if both are signed, then again the expression is equivalent to pos_type(-1)
.
If pos_type
were signed and off_type
were unsigned -- which makes no sense, but bear with me -- then at best this double cast would shove some huge value into pos_type
and at worst it would invoke implementation-defined behavior by assigning a too-large value to the signed pos_type
integer.
Does anyone know the standard's rationale for specifying pos_type(off_type(-1))
here instead of just pos_type(-1)
? If not, can you even imagine a plausible rationale?
I believe that pos_type
by default boils down to a std::streampos
, which is typically defined like this:
typedef fpos<mbstate_t> streampos;
std::fpos
is usually an offset combined with a multi-byte state object.
Additionally, off_type
by default will boil down to a std::streamoff
which is also a signed integral type (long
or something like that)
So I think the mentality here is that you can initialize a offset type with the sentinal -1
value, then that can be used to initialize a position object which is a more complex object. Because, fpos
's constructor takes streamoff
type, not a long
, if streamoff
could be a more complex type than a long
or similar, it would make the cautious-ness necessary.
Imagine an implementation where streamoff
was defined like this:
struct streamoff {
explicit streamoff(long offset);
// rest of the stuff here...
};
Then just pos_type(-1)
wouldn't work because there would be no implicit conversion.
So I think it's just being cautious.
精彩评论