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.
Streams have no copy constructor. You might implement your own or possibly move semantics.
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_ptr
s 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));
}
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));
^~~~~~~ ^~~~
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.