tags:

views:

226

answers:

1

I think I'm failing to understand some finer point of C++. I want to set up a log of what my program does, and discovered std::clog, which seems to do what I want in theory, but in practice it doesn't.

If I do the following, clog works as expected and writes "Test 1" to the screen, and "Test 2" shows up in a file:

int main ()
{
    clog << "Test 1" << endl;
    streambuf* original_buffer = clog.rdbuf (ofstream ("test.log").rdbuf ()));
    clog << "test 2" << endl;

    clog.rdbuf (original_buffer);
    return 0;
}

But if I put all that into a class as such, then "Test 1" is written to the screen, test.log is created, but there's nothing inside and "Test 2" is no where to be found!:

class IerrLog
{
    std::streambuf * original_buffer;
    public:
    IerrLog ()
    {
        std::ofstream logFile ("test.log");
        original_buffer = std::clog.rdbuf (logFile.rdbuf ());
    }
    ~IerrLog ()
    {
        std::clog.rdbuf (original_buffer);
    }
};

int main () {
    clog << "Test 1" << endl;
    IerrLog someLog ();
    clog << "Test 2" << endl;
    return 0;
}

What am I missing?

EDIT: If I run the latter in valgrind, I get errors like this (the former runs clean):

Invalid read of size 8
    at 0x39598993E5: std::ostream::flush() (in /usr/lib/libstdc++.so.6.0.10)
    by 0x395989B5F2: std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&) (in /usr/lib/libstdc++.so.6.0.10)
    by 0x400F8E: main (main.cc:23)
  Address 0x7ff0006c8 is just below the stack ptr.  To suppress, use: --workaround-gcc296-bugs=yes

I'm not obnoxious enough to think that I (a lowly common programmer) found a compiler bug with such a simple program, but this makes me even more confused and valgrind obviously finds that the latter is somehow wrong, even though I tried to make them functionally identical.

+4  A: 

I assume you want to create a stack variable of IerrLog. You need to change

IerrLog someLog ();

to

IerrLog someLog;

Your original statement will be interpreted by the compiler as a declaration of function someLog() which takes no arguments and returns an IerrLog.

You should also create your file as a member variable and not on the stack.

lothar
Wow that was fast. `logFile` being on the stack was indeed the problem!
MighMoS
Not quite--the first line there is interpreted as a declaration of function someLog() which takes no arguments and returns an IerrLog.
Drew Hall
@Drew you are right, I'll fix the answer.
lothar