c++ - CRTP 在父的析构函数中调用子函数

标签 c++ c++11 iostream streambuf

我有两个这样结构的类(简化了代码以更清楚地显示问题):

template<typename stream_type>
class Stream : public std::basic_streambuf<char, std::char_traits<char>>
{
private:
    std::string pBuffer;

    //other functions overridden here..

public:
    Stream();
    virtual ~Stream();

    Stream(const Stream& other) = delete;
    Stream& operator = (const Stream& other) = delete;
};

template<typename stream_type>
Stream<stream_type>::Stream() : pBuffer()
{
    parent_type::setg(nullptr, nullptr, nullptr);
    parent_type::setp(nullptr, nullptr);
}

template<typename stream_type>
Stream<stream_type>::~Stream()
{
    //Parent Destructor calling child member function..
    static_cast<stream_type*>(this)->sync(&pBuffer[0], pBuffer.size());
}


//CRTP Child..
template<typename char_type>
class File : public Stream<File<char_type>>
{
private:
    FILE* hStream;

public:
    File(const char* path) : Stream<File<char_type>>()
    {
        hStream = fopen(path, "w");
    }
    ~File()
    {
        //Child destructor is closing the file..
        fclose(hStream);
    }

    int sync(const char_type* data, std::size_t size)
    {
        if (fwrite(data, sizeof(char_type), size, hStream) == size)
        {
            fflush(hStream);
        }

        return traits_type::eof();
    }
};

问题:

当由于超出作用域而调用子进程的析构函数时,它首先关闭文件。之后,它调用父进程的析构函数。但父进程仍在尝试访问子进程的“同步”功能(当然这是一个错误)..

关于如何解决这种情况的任何想法?我需要父类来保证其缓冲区中的所有数据都同步到磁盘。但是,我的子类可能并不总是"file"类。它可能是另一种不同步的流。我需要父类强制所有子级同步他们的数据。

有什么想法可以做到这一点吗?

最佳答案

成员和基地的销毁顺序与它们创建的顺序相反。
所以一个解决方案可能是围绕 FILE* 有一个包装类,并且有
作为比 Stream 更早的基础,所以它会在以后被销毁;

template<typename char_type>
class File : private CFileWrapper, public Stream<File<char_type>>

关于c++ - CRTP 在父的析构函数中调用子函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56516897/

相关文章:

c++ - 复制到数组时的 memcpy 与赋值;为什么这会生成不同的代码?

c++ - 在 C++ 中,是否可以获取函数的返回类型以便在不调用该函数的情况下声明一个变量?

c++ - 如何在 C++ 中生成给定数组的子集?

c++ - opengl 3.3 中的黑屏输出

c++ - 无法获得与 POCO 一起使用的并发 HTTPS 请求

c++ - "Capture"lambda 函数中的变量解析为参数

c++ - 为什么空 streambuf 的流插入失败?

c++ - 使用 std::ifstream,忽略字符和查找之间有区别吗?

c++ - gcc std::istream 'error: invalid cast from type ‘std::streamsize’ 键入 ‘std::streamsize’ '

c++ - 通过指针传递引用