- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个简单的问题。我有一个要写入数据的 ofstream。完成并调用 close()
后,我需要在句柄上调用 delete
还是 close()
执行清理?
例如:
mFileStream = new std::ofstream(LogPath.c_str(), std::ios::trunc);
...
mFileStream->Close();
//delete mFileStream?
我的直觉是肯定的,因为我已经分配了它,但我不确定我在哪里读到它。谁能解释一下?
最佳答案
是的,你必须这样做。在 C++ 中,您必须将 new
和 delete
配对。
虽然,在像这样的简单情况下您不需要,您可以在堆栈上分配您的对象,它会为您销毁,强烈建议这样做(更快更安全):
{ // enclosing scope (function, or control block)
ofstream mFileStream(LogPath.c_str(), std::ios::trunc);
...
mFileStream.close(); // mFileStream is not a pointer any more, use the "." operator
// mFileStream destroyed for you here. "close" may even be called for you.
}
小提示:close
带有一个小“c”。
关于c++ - ofstream - 需要在 close() 操作后删除对象句柄吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9541897/
我想在一个函数中打开一个文件,将打开的文件对象返回给 main,并在另一个函数中使用它函数来填充文件。编译器似乎告诉我,我正在尝试访问 iostream 的私有(private)成员。有没有办法做到这
我最近写了一个记录器类。编译这段代码时: std::ofstream *stream = new std::ofstream; stream->open( log_file_name.c_str()
我有以下测试代码,其中有一个参数 fS,它是 ofstream 的容器: #include #include #include #include int
我正在尝试实现一个记录器,它可以注册到多个流,如 ostringstream、ofstream 等。我试图实现这样的功能 void register_stream(std::ostream& a);
我有一个在线程上写入文件的类 class A{ public: void writeToFile(ofstream& outFile, obj &a) { //...
我有以下代码 void _log_message(const char* fmt, ...) { va_list arg; ofstream logfile; cout << "Open Lo
我刚刚开始阅读如何打开和编辑文件。使用 ifstream 时,如果文件不存在,则不会创建它。 引用下面的代码,条件 (!outfile) 何时为假,就好像文件不存在一样,构造函数将简单地创建它,因此总
#include #define LOGFATAL(msg) log(0, msg) std::ofstream *logst = NULL; void log(int sev, char *msg
我在使用 ofstream 时遇到问题一次将两个不同的输出写入两个不同的文件。程序编译运行正常,并向p1output.txt写入数据,但是当我打开p2output.txt时,除了第一行内容外是空白的:
我有一个“资源模块”类来管理我的应用程序的所有资源,它主要从一个包含所有内容的文件“RESOURCES.DAT”中读取。 从文件中请求新数据的所有对象都通过 ResourceModule,因此我可以管
我遇到流问题,程序无法打开我要写入的文件。最小完整可变代码如下: #include #include using namespace std; int main(){ string roo
我已经研究了好几个小时了,我只知道答案很简单。似乎无论我做什么我都无法打开文件。这是一个多类程序,所以在标题中我有 #include #include class A{ string path
所以我想写一个可以像这样使用的缩进输出类: Debug f; f.open("test.txt"); f }' and '') ofs #include using namespace std;
大家好... 抱歉我的英语不好,但是会说西类牙语... 这周,为了这个proyect的学习和工作,我想创建一个软件来制作文件(.us)... 示例 char name[50]; //Or string
我不想在 main() 中构造 ofstream。这是我所做的,但它没有编译: #include using namespace std; class test { private: ofs
谁能告诉我这是怎么回事? #include #include #include #include #include class writeManager { std::vector
我有一个 C++ 类,它将其数据写出到二进制 std::ofstream。该类将数据存储为 boost:shared_array 但我已经消除了这个问题。问题出在 ofstream 上对 write(
在我的程序中,我的 dataout: void outfile 没有写入文件,任何人都可以找出原因吗? using namespace std; #include #include #include
我想在文件上写点东西。但它只是没有像它必须假设的那样编写。 void main() { int accno; char name[20]; float deposit;
我遇到了一个奇怪的问题。我有两个函数,它们都有一个通过引用传递的 ofstream。但是,当我调用第二个函数时,正在打印第一个函数的一部分。 这是第一个函数: void GamePlay::dealD
我是一名优秀的程序员,十分优秀!