[英]CRTP call child function in destructor of parent
我有两个类似的结构(简化代码以更清楚地显示问题):
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*
,并且有
它作为比Stream
更早的基础,以便以后被销毁;
template<typename char_type>
class File : private CFileWrapper, public Stream<File<char_type>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.