2

I have a function that is coded to output text to standard output when the destructor of the global basic_ostream object is called. I've registered this function on the stream but for some reason it doesn't do anything:

void callback(std::ios_base::event evt, std::ios_base& str, int index)
{
    if (evt == std::ios_base::erase_event)
    {
        std::cout << "Erase event";
    }
}

int main()
{
    std::cout.register_callback(callback, index());
}

There are no errors/warnings and it doesn't output anything unless I add an explicit call to the destructor:

std::cout.~basic_ostream<char>(); // "Erase event"

I realize that doing so is wrong so I won't count that as a workaround. I've even tried flushing the output from the buffer but to no avail. Why is this happening? I'm running my code on GCC 4.8. Here is a demo.

David G
  • 94,763
  • 41
  • 167
  • 253
  • Static instances are usually destroyed after main returns: http://stackoverflow.com/a/2204628/1175253. I placed a breakpoint within that handler and in libstdc++, they won't get hit without that explicit destructor call. I guess, that since this instance is not 'managed' by your code, its not just elided, it simply gets dropped. I can't seem to find an exit handler, which does anything in libstdc++, but there is a lower level IO cleanup function for flushing. – Sam Nov 03 '13 at 01:12

1 Answers1

1

You are trying to use std::cout to output text while std::cout is being destroyed? Please don't tell me that that is supposed to work...

  • Can you prove to me that it won't work? Maybe the callback is called before any other operations are performed. Besides, the documentation says that the underlying stream buffers are not touched by the destructor, implying that it might work. – David G Nov 03 '13 at 01:33