我有两个这样结构的类(简化了代码以更清楚地显示问题):
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/