矢量的ofstream指针

Jor*_*ama 5 c++ error-handling pointers vector ofstream

这是我的问题,我需要创建X个文件并根据不同的事实写入它们,我的解决方案是创建一个像这样的ofstream指针向量

#include <boost/algorithm/string.hpp>
#include <vector>
#include<string>
#include <iostream>
#include <fstream>
vector<ofstream*> files;
files.resize(SplitVec.size()-4);
          for(i=0;i<SplitVec.size()-4;i++)
          {
              line="/Users/jorge/Desktop/testing/strain_"+lexical_cast<string>(i);
              cout<<"ine"<<endl;
              files[i]=new ofstream(line.c_str());
          }
Run Code Online (Sandbox Code Playgroud)

直到这一部分,它创建文件很好,后来在程序中我写给他们,这也很棒,我的问题是当我想要关闭对象,如果我使用:

for(i=0;i<SplitVec.size()-4;i++)
          {
              *files[i].close();
          }
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

In file included from main.cpp:14:./methyl.h:298: error: request for member 'close' in 'files. std::vector<_Tp, _Alloc>::operator[] [with _Tp = std::ofstream*, _Alloc = std::allocator<std::ofstream*>](1ul)', which is of non-class type 'std::ofstream*'
Run Code Online (Sandbox Code Playgroud)

所以,我有一个问题,首先,为什么我不能调用close,它是指向ofstream的指针,所以使用*files [i],我会想象我可以关闭它,其次,如果我不关闭它,程序工作正常,但我几乎可以肯定,这是一个不好的做法,不想成为一个懒惰或蹩脚的程序员,我尽可能多地看,但我没有找到答案.谢谢!!!

Luc*_*ore 9

使用

(*files[i]).close();
Run Code Online (Sandbox Code Playgroud)

或直接

files[i]->close();
Run Code Online (Sandbox Code Playgroud)

  • @JorgeKageyama因为优先权.它被解析为`*(files [i] .close())`. (4认同)

Mr.*_*C64 5

您的代码不是异常安全的(例如,如果抛出异常,因为您有一个原始指针向量,它们被泄露 - 带有相关的流句柄).

我建议采用现代C++ RAII方法.

例如,如果使用一个智能指针等shared_ptr(从升压,或从C++ 11 <memory>头),就可以建立一个vectorshared_ptr的,并使用make_shared分配的ofstream对象:

// RAII exception-safe approach
vector<shared_ptr<ofstream>> files;

// Add a new ofstream object to the vector:
files.push_back( make_shared<ofstream>( filename ) );
Run Code Online (Sandbox Code Playgroud)

当向量超出范围时,它会被破坏,并且所有指向的流对象都会自动释放:非常简单,清晰且异常安全.

如果你想在向量超出范围之前强制清理流,你可以.clear()在向量上调用方法.

(一种替代方法可能是使用C++ 11 move-semantics- powered unique_ptr,并定义一个vector<unique_ptr<ofstream>>,但遗憾的是没有标准等效的make_sharedfor unique_ptr,并且代码可能会更冗长,除非你编写自定义实现make_unique,如Herb Sutter提出的那个.)

请注意,通常的files[i]->close()语法也适用于智能指针向量的情况.