From cppreference.com
basic_ios©fmt(constbasic_ios&other);If other refers to the same object as *this, has no effects. Otherwise, copies the state of the stream other into *this. This is done in the following sequence:
2) Copies all member objects from other to *this except for
, the exception mask, and
. In particular, makes copies of the locale, the formatting flags, the contents of the arrays
and
(but not the iword and pword pointers themselves), the callbacks, and the tied stream.
4) Copies the exception mask from other to *this as if by calling exceptions(other.exceptions()).
Parameters
other - another stream to use as source Return value
*this
Notes
The second pass through the callbacks may be used to deep-copy the user-defined objects pointed to by the pointers in
.
copyfmt() may be used to save and restore the state of a stream. Boost provides a more fine-grained
library for the same purpose.
Example
Makes the
object "out" behave exactly like
, including formatting,
to
, etc.
Run this code
#include<bitset>#include<climits>#include<fstream>#include<iostream>intmain(){std::ofstreamout;out.copyfmt(std::cout);// copy everything except rdstate and rdbufout.clear(std::cout.rdstate());// copy rdstateout.basic_ios<char>::rdbuf(std::cout.rdbuf());// share the bufferout<<"Hello, world\n";autobin=[](std::ios_base::fmtflagsf){returnstd::bitset<sizeof(std::ios_base::fmtflags)*CHAR_BIT>{static_cast<unsignedlonglong>(f)};};std::ofstreamout2;std::cout<<"1) out2.flags(): "<<bin(out2.flags())<<'\n';std::cout<<"2) cout.flags(): "<<bin(std::cout.flags())<<'\n';std::cout.setf(std::ios::hex|std::ios::fixed|std::ios::boolalpha);std::cout<<"3) cout.flags(): "<<bin(std::cout.flags())<<'\n';out2.copyfmt(std::cout);// copy everything except rdstate and rdbufstd::cout<<"4) out2.flags(): "<<bin(out2.flags())<<'\n';}Possible output:
Hello, world 1) out2.flags(): 00000000000000000001000000000010 2) cout.flags(): 00000000000000000001000000000010 3) cout.flags(): 00000000000000000001000000001111 4) out2.flags(): 00000000000000000001000000001111 Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR Applied to Behavior as published Correct behavior
C++98 step 3 called the registered callbacks with the
event type copy_event, which is not defined corrected to
C++98 if other refers to the same object as *this, the member objects
were still copied and the registered callbacks were still called do nothing
in this case