问题
Loki Astari provides this custom steam buffer. How can I change the class to automatically flush when reading from cin::cin or when the application exists? For example:
int main ()
{
MyStream myStream(std::cout);
myStream << "This does not print.";
}
and
int main()
{
MyStream myStream(std::cout);
myStream << "This does not print.";
std::cin.get();
}
whereas
std::cout << "This does print.";
and
std::cout << "This does print.";
std::cin.get();
If I force it
myStream << "This will now print." << std::flush;
However, I am hoping to replicate the cout behavior of triggering at program exit or std::cin automatically.
This works (thanks to Josuttis's "The C++ Standard Library"):
MyStream myStream(std::cout);
std::cin.tie(&myStream);
myStream << "This will now print.";
std::cin.get();
because std::cint.tie(&std::cout)
is a predefined connection.
Question #1: Can I modify the MyStream class to tie it to the cin stream so that I do not have to issue a std::cin.tie(&myStream)
every time I create an instance?
Question #2: How can the MyStream class be modified so that the buffer will be automatically flushed at program exit?
回答1:
- Constructors are designed to do things at object creation time, so it would be appropriate to establish the tie in the constructor of
MyStream
:std::cin.tie(this);
. This will probably break any tie that exists betweencin
andcout
, and.or betweencin
abd another instance of your stream class. - For doing things at program exit, C++ has destructors of objects with static storage duration.
来源:https://stackoverflow.com/questions/17532460/can-a-custom-stream-buffer-automatically-flush-at-program-exit-and-when-requesti