Quick Links:

bal | bbl | bdl | bsl

Namespaces

Component bslim_formatguard
[Package bslim]

Provide a guard for saving the state of a stream object. More...

Namespaces

namespace  bslim

Detailed Description

Outline
Purpose:
Provide a guard for saving the state of a stream object.
Classes:
bslim::FormatGuard format guard for stream types.
Description:
The bslim::FormatGuard type saves the configuration of a basic_ostream type, when the guard is created. When the guard is destroyed, the stream is restored to the state it was in when the guard was created.
The state that is saved is
  • The fmtflags state
  • The floating-point precision
  • The fill char
Note that the width field is not saved, because it does not normally persist among multiple items output, but automatically resets to 0 after a single item is ouput.
Usage:
In the following example we illustrate the usage of FormatGuard.
Example 1: Saving Stream State to be Restored Later:
Suppose we want to do some output to a stream for which we must change the state of the stream.
First, we declare our stream: Then, we use a FormatGuard to save the state of oss before we reconfigure it, so that when the FormatGuard is destroyed it will resotre oss to its original state.
  {
      bslim::FormatGuard guard(&oss);
Then, we reconfigure out stream and do some output:
      oss << "First line in hex: " << bsl::showbase << bsl::hex << 80 <<
                                                                        endl;
Next, we leave the block and the destructor of guard will restore oss to its original configuration:
  }
Now, we do another line of output:
  oss << "Second line in decimal: " << 123 << endl;
Finally, we observe that our guarded output was in hex, as desired, and the output afterward was in decimal, as desired:
  assert(oss.str() == "First line in hex: 0x50\n"
                      "Second line in decimal: 123\n");