在销毁派生的std::basic_ostream时出现分段错误
Segmentation fault when destructing a derived std::basic_ostream
我是从std::basic_ostream
派生的,因为我需要改变底层文件缓冲区的创建方式。(我需要一个唯一的文件名,我可以查询,以便文件可以在关闭时删除;即不能使用std::tmpnam
或std::tmpfile
。)我已经尝试过了(见下文),但是我在销毁时遇到了分割错误。
什么原因导致分割错误?似乎我没有为文件缓冲区分配内存,或者我删除了它两次。
// Compile with
// clang++ -std=c++14 -stdlib=libc++ main.cpp -o tmpFile
//
#include <iostream>
#include <fstream>
#include <string>
#include <streambuf>
using namespace std;
template< class charT, class traits=char_traits<charT> >
class FILE_streambuf : public std::basic_streambuf<charT, traits> {
public:
FILE_streambuf(std::string& filename)
{
filename = "chicken";
buffer_ = fopen(filename.c_str(), "wx");
}
virtual ~FILE_streambuf(){
fclose(this->buffer_);
}
FILE* buffer_;
};
template< class charT, class traits=char_traits<charT> >
class tmp_ofstream : public basic_ostream<charT, traits>{
public:
tmp_ofstream()
: filename_("")
{
try{
this->rdbuf(new FILE_streambuf<charT, traits>(filename_));
} catch (const std::exception& e){
throw e;
}
}
~tmp_ofstream(){
delete this->rdbuf();
remove( filename_.c_str() );
}
std::string filename() { return this->filename_; };
std::string filename_;
};
int main(){
tmp_ofstream<char> tmpStream;
cout << "tmpStream has filename: " << tmpStream.filename();
cout << "n-----------------------------------------n";
return 0;
}
正如Igor Tandetnik所指出的那样,代码隐式调用std::basic_ostream
的默认构造函数,该构造函数不应该存在。代码使用libc++编译,因为后者提供了这样一个(受保护的)默认构造函数作为扩展:
basic_ostream() {} // extension, intentially does not initialize
如果tmp_ofstream
的构造函数调用std::basic_ostream
的标准认可构造函数,问题就消失了:
tmp_ofstream()
: basic_ostream<charT, traits>(0) // Sic!
, filename_("")
{
try{
this->rdbuf(new FILE_streambuf<charT, traits>(filename_));
} catch (const std::exception& e){
throw e;
}
}
相关文章:
- 在抛出 'std::runtime_error' 的实例后终止调用 what(): Filebuf 和 ostream 的 I/O 错误
- boost::interprocess::file_lock 与 std::ostream 一起使用时的错误行为
- 从 std::ostream 重载 << 运算符时,为什么编译器会给出"too many parameters for this operator function"错误?
- 运算符的歧义错误<<自定义 std::ostream 子类中的重载
- 打印矩阵后分割错误,但在打印额外行后修复(ostream <<操作器)
- ostream 运算符<<错误C++
- 尝试重载时'ostream'和'istream'错误C++
- C++,错误:" no operator "== " matches these operands ",ostream/istream
- 为什么在重载的 ostream 运算符中引用 lambda 中的向量会导致错误
- C++以友元身份重载 ostream 运算符会导致错误:变量在此上下文中是私有的
- 当我编译引用 std::ostream 时,我有一个奇怪的错误弹出
- 将 ostream 作为引用传递时出现错误
- 错误:无法将"std::ostream {aka std::basic_ostream<char>}"lvalue 绑定到"std::basic_ostream&<char>&
- high_resolution_clock错误:无法将"std::ostream {aka std::basic_ostream}"<char>lvalue 绑定到"std::basic_
- 错误:非静态引用成员"std::ostream&Student::out",无法使用默认赋值运算符
- C++ istream >> 和 ostream << 错误
- 错误:无法在实现文件中绑定“std::ostream”
- 错误:“oStream”未命名类型
- oStream&没有命名类型错误。我在这里做错了什么?
- C++编译器错误,涉及从类型为"std::ostream"的临时引用初始化类型为"std::ostream"的非常量引用