为什么我可以有一个std::vector<std::ofstream*>而不是std::vector<std::ofstream>?
Why can I have a std::vector<std::ofstream*> but not a std::vector<std::ofstream>?
我有以下测试代码,其中我有一个参数fS
,它是ofstream
s的容器:
#include <fstream>
#include <vector>
#include <cstdlib>
#include <cstdio>
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(of);
return 0;
}
这根本无法编译。然而,当我将ofstream
的容器更改为指向ofstream
s的指针的容器时,代码编译为:
#include <fstream>
#include <vector>
#include <cstdlib>
#include <cstdio>
int main()
{
// my container of ofstream(s)
std::vector<std::ofstream*> fS;
// instantiate an ofstream
std::ofstream * of = new std::ofstream("myfile.txt");
// push back to my container
fS.push_back(of);
return 0;
}
为什么会这样?
当您在vector
上调用push_back(of)
时,它会尝试将对象of
的副本添加到向量中。(c++喜欢复制东西)。在这种情况下,您试图复制ofstream
,这是不允许的。直观地说,拥有一个ofstream
的副本意味着什么并不清楚,所以规范禁止它。
另一方面,假设您有vector
的ofstream*
s。现在,如果您尝试push_back
指向ofstream
的指针,那么c++将其解释为您应该将指针的副本放入vector
中,这没关系,因为指针可以很容易地复制。
如果你有一个最新的编译器,还有第三个选择。c++最近引入了移动语义的思想,即与其尝试将文件流复制到vector中,不如将文件流移动到vector中。因此,您可以这样写:
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;
}
这样做之后,变量of
将不再引用原始文件流;它只会有一个虚拟值。但是,vector现在将有效地包含以前存储在of
中的流。
相关文章:
- std::ofstream 作为类成员删除复制构造函数?
- C++:std::ofstream 方法 open() 在第二次迭代时擦除打开的 ifstream 文件
- 如何在 std::ofstream 和 std::cerr 之间切换
- 为什么将字符串输出到未命名的 std::ofstream 反而给了我一个十六进制数?
- 如何使用 std::cout 或 std::ofstream 作为单个函数的输入?
- 将 boost stream_buffer 与 std::ofstream 结合使用
- 对 std::ofstream 进行空文件检查
- 将 std::ofstream 对象作为参数传递给类方法
- 为什么 std::ofstream 会在没有 std::ios_base::trunc 的情况下截断?
- std :: ofstream,覆盖错误的文件行
- std :: ofstream-没有比1023(即时冲洗)更长的缓冲字符串
- 如何超载std :: ofstream :: put()
- 返回"Cannot convert from 'std::ofstream {aka std::basic_ofstream<char>}' to bool"错误
- std::ofstream 会自动在 之后添加回车符 (CR; \r)
- std::ofstream 追加文件
- 使用std:ofstream时,将目录的副本检查到文件中
- C++线程:无法将参数 1 从 'const std::ofstream' 转换为 'std::ofstream &'
- 为浮点数配置std :: ofStream格式
- 重定向std:cout到std::ofstream,得到一个错误
- 使用std :: ofstream中的c 中的float变量输出