C ++ steam objects have state. If you write a piece of code, for example
using namespace std; cout << hex << setw(8) << setfill('0') << x << endl;
forget to set the flow state back. This will cause problems in some other unrelated codes. It is satisfactory to pair the “set” and “cancel” pairs. In addition, it seems to me that this is also against the convention for RAII.
My question is: is it possible, only with a thin layer of wrapping, to make these manipulations with the RAII-like mode. That is, immediately after the expression ends with a semicolon, the state of the stream automatically returns to default.
Update: via the link provided by @ 0x499602D2, one of the ways could be something like
#include <boost/io/ios_state.hpp> #include <ios> #include <iostream> #include <ostream> #define AUTO_COUT(x) {\ boost::io::ios_all_saver ias( cout );\ x;\ }while(0)
Then you can use the macro as
AUTO_COUT(cout << hex << setw(8) << setfill('0') << x << endl);
By the way, it might be a good idea to add a lock field to that class saver boost :: io :: ios_state, in case funny things happen in a multi-threaded program. Or have they already done this?
source share