C++03 standard tells us that the result of applying the bitwise shift operators to signed types can be UB and Impl. defined for ne开发者_JAVA技巧gative values. My question is following: why for operator <<
it has undefined behaviour, while for operator >>
it is just implementation defined ? Is there a strict reason why the result of <<
couldn't be implementation defined also ?
According to 5.8/2 (admittedly in C++ 98 which is all I have access to):
The value of E1 << E2 is E1 (interpreted as a bit pattern) left shifted E2 bit positions; vacated bits are zero filled. If E1 has an unsigned type, the value of the result is E1 multiplied by the quantity 2 raised to the power E2, reduced modulo ULONG_MAX+1 if E1 has type unsigned long, UINT_MAX+1 otherwise.
From this it looks to me like it's perfectly well defined for left shift. What's not defined is the representation of signed values (such as twos-complement) used so the numeric value of the result is implementation defined for negative values.
This is in contrast to right-shifting where the vacated bits may be zero or one filled depending on the representation of signed values.
精彩评论