Can a custom stream buffer automatically flush at program exit and when requesting input?

大兔子大兔子 提交于 2019-12-12 02:28:15

问题


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:


  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 between cin and cout, and.or between cin abd another instance of your stream class.
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!