1

I got error "C2280: attempting to reference a deleted function" compiling error when doing following code:

std::ofstream ofs(m_headerFileName, std::ios::binary, std::ios_base::app);
            m_ofsHeader.push_back(ofs);

where

std::vector<std::ofstream>      m_ofsHeader;

I don't understand why I cannot push a ofstream instance into an ofstream vector. Someone gives some hint? Thanks. I am on Windows 7 and Visual Studio 2015. Also, what is the walkaround here if there is any?

I am trying to keep a bunch of ifstream/ofstream with each one having their own file to read/write.

Nick X Tsui
  • 2,737
  • 6
  • 39
  • 73

3 Answers3

4

First of all, the following is wrong, because there is no std::ofstream constructor taking three arguments:

std::ofstream ofs(m_headerFileName, std::ios::binary, std::ios_base::app);

You probably meant:

std::ofstream ofs(m_headerFileName, std::ios::binary | std::ios::app)

And then, there's the storage problem. Streams cannot be copied, that's why your push_back fails.

You could just move the streams instead:

#include <fstream>
#include <vector>
#include <ios>

int main()
{
    std::vector<std::ofstream> streams;

    std::ofstream os("foo.txt", std::ios::binary | std::ios::app);
    streams.push_back(std::move(os));
}

Note the std::move, which casts os so that the && overload of push_back is used.

Or you store std::unique_ptrs to the streams in the vector:

#include <fstream>
#include <memory>
#include <vector>
#include <ios>

int main()
{
    std::vector<std::unique_ptr<std::ofstream>> streams;

    auto os = std::make_unique<std::ofstream>("foo.txt", std::ios::binary | std::ios::app);
    streams.push_back(std::move(os));
}
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
3

Streams have no copy constructor. You might implement your own or possibly move semantics.

Dumbo
  • 13,555
  • 54
  • 184
  • 288
  • 1
    *"You might implement your own"* - What do you mean? You cannot implement your own copy constructors for standard classes. – Christian Hackl Dec 15 '17 at 16:45
  • @ChristianHackl Hmmm...driving from stream and overwriting thing like overflow, underflow, etc...it is gonna be hard but still possible (and by the time of my answer it was not clear what OP wants hence the XY problem occurred) – Dumbo Dec 15 '17 at 20:07
2

Streams cannot be copied. Their copy constructor and copy assigner are mark as delete. Consider using move semantics as well as std::vector::emplace_back():

m_ofsHeader.emplace_back(std::move(ofs));
            ^~~~~~~      ^~~~
iBug
  • 35,554
  • 7
  • 89
  • 134