Search code examples
c++stlraiiiostream

Using RAII with C++ streams and STL containers?


I'm trying to use RAII concepts with an STL container of ofstream objects. For example:

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();
}

However, no matter how I try to tweak the code and declarations, the compiler always complains. Apparently the copy constructor for std::basic_ios, which lives inside of streams, is private. Are there any easy plian C++/STL solutions to doing this using RAII, or do I need to get some type of smart pointer involved?


Solution

  • In the interest of keeping a file from being written to in multiple places in various parts of the system, streams are noncopyable. A smart pointer is probably the way to go here.