Question

Is it perfectly ok (= well defined behaviour according to the standard) to call :

mystream.read(buffer, 0);

or

mystream.write(buffer, 0);

(and of course nothing will be read or written). I would like to know if I have to test if the provided size is null before calling one of these two functions.

Was it helpful?

Solution

Yes, the behavior is well-defined: both functions will go through the motions for unformatted input/output functions (constructing the sentry, setting failbit if eofbit is set, flushing the tied stream if necessary), and then they will get to this clause:

§27.7.2.3[istream.unformatted]/30

Characters are extracted and stored until either of the following occurs:

— n characters are stored;

§27.7.3.7[ostream.unformatted]/5

Characters are inserted until either of the following occurs

— n characters are inserted;

"zero characters are stored/inserted" is true before anything is stored or extracted.

Looking at actual implementations, I see for (; gcount < n; ++gcount) in libc++ or sgetn(buffer, n); in stdlibc++ which has the equivalent loop

OTHER TIPS

Another extraction from 27.7.2.3 Unformatted input functions/1 gives us a clue that zero-size input buffers are valid case:

unformatted input functions taking a character array of non-zero size as an argument shall also store a null character (using charT()) in the first location of the array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top