使用自定义复制构造函数创建包含 std::ofstream 的类的 std::vector

问题描述 投票:0回答:0

我目前正在尝试使用 std::ofstream 编写一个日志类来写入文件。课程如下:

#ifndef LOG_H
#define LOG_H

#include <fstream>
#include <vector>

class Log
{
    public:
        std::ofstream *outFile = new std::ofstream;
        
        Log(){}

        Log(const Log &logIn) 
        {
            outFile = std::move(logIn.outFile);
        }

        Log(const char* location)
        {
            outFile->open(location);
        }

        void log(const char* input)
        {
            if(outFile)
            {
                *outFile << input << std::endl;
            }
        }

        void endLog()
        {
            outFile->close();
        }
};

#endif

我在这里使用 ofstream* 的原因是因为 std::move。这也意味着我需要调用“new std::ofstream”,否则它会创建一个 SEGFAULT。

我的主图是这样的:

#include "Log.h"

int main()
{
    Log testLog("./logs/testlog.log");
    
    std::vector<Log> logs;
    logs.resize(1);
    logs.emplace_back(testLog);
    logs.at(0).log("testtesttesttest");

    logs.at(0).endlog();
}

我正在使用 gcc 12.2.1 20230201 来编译这个程序。

如果我创建 Log 的单个实例,文件将被创建和写入而不会出现问题,但是创建 Log 对象的 std::vector 不会导致任何内容被写入,这让我相信 std::move 运算符不是正确移动流。

任何帮助将不胜感激。

c++ logging ofstream
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.