Why don't my changes clog the stick?

I don't think I understand some more subtle point of C ++. I want to create a log of what my program is doing and I found std::clog

that it seems to do what I want in theory, but in practice it is not.

If I do the following, the shutter works as expected and writes "Test 1" to the screen, and "Test 2" appears in the 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 this in a class as such, then "Test 1" will be displayed on the screen, test.log will be created, but there is nothing inside, and "Test 2" is not 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 first one works 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 nasty enough to think that I (a low common programmer) encountered a compiler error with such a simple program, but this confuses me even more and it seems valgrind thinks the latter is somehow wrong, even though I tried to make them functionally identical.

0


a source to share


1 answer


I am assuming that you want to create a stack variable IerrLog. You need to change

IerrLog someLog ();

      

to



IerrLog someLog;

      

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

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

+4


a source







All Articles