如何实现作用域的iostream格式?

pil*_*row 4 c++ formatting scope iostream

我想限制C++中I/O流格式的影响,以便我可以这样做:

std::cout << std::hex << ...
if (some_condition) {
  scoped_iofmt localized(std::cout);

  std::cout << std::oct << ...
}
// outside the block, we're now back to hex
Run Code Online (Sandbox Code Playgroud)

以便在离开块时将基准,精度,填充等恢复到先前的值.

这是我提出的最好的:

#include <ios>

class scoped_iofmt
{
    std::ios& io_;     // The true stream we shadow
    std::ios  dummy_;  // Dummy stream to hold format information

    public:
    explicit scoped_iofmt(std::ios& io)
                : io_(io), dummy_(0) { dummy_.copyfmt(io_); }
    ~scoped_iofmt() { try { io_.copyfmt(dummy_); } catch (...) {} }
};
Run Code Online (Sandbox Code Playgroud)

...但是c ++ iostream是一个相当棘手的领域,我不确定上述的安全性/适当性.危险吗?你(或有第三方)已经做得更好了吗?