简体   繁体   English

为什么我的木log不改?

[英]Why doesn't my change to clog stick?

I think I'm failing to understand some finer point of C++. 我想我无法理解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. 我想建立一个程序执行情况的日志,并发现std::clog ,它在理论上似乎std::clog我的要求,但实际上却没有。

If I do the following, clog works as expected and writes "Test 1" to the screen, and "Test 2" shows up in a file: 如果执行以下操作,则阻塞将按预期方式工作并将“ Test 1”写入屏幕,并且在文件中显示“ Test 2”:

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!: 但是,如果我将所有内容放到这样的类中,则将“ Test 1”写入屏幕,创建了test.log,但是里面什么也没有,并且“ Test 2”也找不到了!:

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): 编辑:如果我在valgrind中运行后者,我会得到这样的错误(前者运行干净):

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. 我还不足为奇,以为我(一个不太普通的程序员)发现了一个如此简单的程序的编译器错误,但是这使我更加困惑,而valgrind显然发现后者是某种程度上的错误,即使我试图这样做也是如此。它们在功能上是相同的。

I assume you want to create a stack variable of IerrLog . 我假设您要创建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. 您的原始语句将由编译器解释为函数someLog()的声明,该声明不带任何参数并返回IerrLog。

You should also create your file as a member variable and not on the stack. 您还应该将文件创建为成员变量,而不是在堆栈上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM