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

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"类。这可能是另一种不同步的流。我需要家长类来强制所有 child 同步他们的数据。

有什么想法可以做到吗?

最佳答案

成员和基础按照创建时的相反顺序销毁。
因此,一种解决方案可能是在FILE*周围有一个包装器类,并
作为比Stream更早的基础,以便稍后将其销毁;

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

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

10-14 09:18
查看更多