C++ std::vector<ofstream> 来看看想把文件流当做容器成员怎么搞?

本博客内容搬运自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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值