使用RAII与C++流和STL容器?

Ogr*_*m33 2 c++ iostream stl raii

我正在尝试将RAII概念与STL容器的ofstream对象一起使用.例如:

int main(int argc, char**argv)
{
  std::deque<std::ofstream> sList;

  sList.push_back(std::ofstream()); // tried variations such as *(new ofstream())
  sList[0].open("test1.txt");
  sList[0] << "This is a test";
  sList[0].close();
}
Run Code Online (Sandbox Code Playgroud)

但是,无论我如何尝试调整代码和声明,编译器总是抱怨.显然,生活在流内部的std :: basic_ios的拷贝构造函数是私有的.使用RAII是否有任何简单的plian C++/STL解决方案,或者我是否需要涉及某种类型的智能指针?

Vic*_*let 5

标准库容器存储值的副本,而不是值本身.因此,你不得不使用可复制的对象(在这种情况下,智能指针).

另一种选择是boost::ptr_vector作为精确针对这种情况的指针向量.