C++ std::ofstream 类成员

loa*_*tes 2 c++ stdout

第一次投稿,但我相信我已经正确检查了过去的帖子,但没有找到有效的解决方案。我正在使用 Visual Studio 2012...

本质上,我想要做的就是将输出流式传输到对象拥有的日志文件。我不知道应该如何精确地实现这一点,但档案中没有任何内容。

据我了解,这个公认的解决方案应该有效:

#include <fstream>
// classA.h
class A {
private:
    std::ofstream * _logfile;
public:
    A(void);
    void dosomething(void) const;
}
Run Code Online (Sandbox Code Playgroud)

// classA.cpp
#include classA.h
A::A(void) : _logfile(0) {
    std::ofstream output("logfile.txt",std::ofstream::app);
    _logfile = &output;
}

A::dosomething(void) {
    *_logfile << "Print something" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

// main.cpp
int main() {
A a = new A();
a->dosomething();
}
Run Code Online (Sandbox Code Playgroud)

这编译没问题,但只是挂起。我猜最有可能是因为输出在 ctor 结束时消失了。实现此功能的好方法是什么?其他 StackOverflow 建议读取导致编译器错误...

谢谢,克里斯

hmj*_*mjd 5

代码具有未定义的行为,就像构造后_logfile悬空指针一样A因为它采用的地址output是在 的构造函数中定义的局部变量A:当A的构造函数完成时,它会output被破坏。_logfile然后在 中取消引用do_something(),这是未定义的行为并且是挂起的可能原因。

要解决,只需使用std::ofstream成员并使其A不可复制(因为流不可复制,但可移动):

class A {
private:
    std::ofstream _logfile;
    A(const A&);
    A& operator=(const A&);
public:
    A() : _logfile("logfile.txt",std::ofstream::app) {}
    void dosomething()
    {
        _logfile << "Print something" << std::endl;
    }
};
Run Code Online (Sandbox Code Playgroud)