本博客内容搬运自stack overflow
今天需要一个动态的增加或删除多个文件流的功能,于是想把vector和ofstream一起用,就像这样:
std::vector<ofstream> chtempStream;
但是不行,提示我错误 C2280 引用已删除的函数
然后我试着改成这样
std::vector<std::ofstream*> fS;
std::ofstream * of = new std::ofstream("myfile.txt");
fS.push_back(of);
跑通了。。。
我就寻思为啥,然后在一个国外论坛上找到了比较好的解答
When you call push_back(of) on a vector, it tries to add a copy of the object of to the vector. (C++ loves making copies of things). In this case, you’re trying to copy an ofstream, which isn’t permitted. Intuitively, it’s not clear what it would mean to have a copy of an ofstream, so the spec prohibits it.
On the other hand, suppose you have a vector of ofstream*s. Now, if you try to push_back a pointer to an ofstream, then C++ interprets this to mean that you should put a copy of the pointer into the vector, and that’s okay because pointers can easily be copied around.
There’s a third option, though, if you have a recent compiler. C++ recently introduced the idea of move semantics, that instead of trying to copy the file stream into the vector, you can move the file stream into the vector. You could therefore write something like this:
int main()
{
// my container of ofstream(s)
std::vector<std::ofstream> fS;
// instantiate an ofstream
std::ofstream of("myfile.txt");
// push back to my container
fS.push_back(std::move(of));
return 0;
}
After doing this, the variable of won’t refer to the original file stream anymore; it’ll instead just have some dummy value. However, the vector will now effectively contain the stream that used to be stored in of.
大概的意思的就是复式构造函数出了问题,不使用指针的时候,你的文件流指向的东西不明确。但是当你用指针时可以,因为指针本质是地址嘛。
然后这大神又给出了使用move函数的方法,也是可以的。
原文地址:https://stackoverflow.com/questions/31885704/why-can-i-have-a-stdvectorstdofstream-but-not-a-stdvectorstdofstream