[英]Why can I have a std::vector<std::ofstream*> but not a std::vector<std::ofstream>?
I have the following test code in which I have a parameter fS
which is a container of ofstream
s: 我有以下测试代码,其中有一个参数
fS
,它是ofstream
的容器:
#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;
}
This does not compile at all. 这根本不编译。 Whereas when I change the container of
ofstream
into a container of pointers to ofstream
s, the code compiles: 而当我将
ofstream
的容器更改为指向ofstream
的指针的容器时,代码将进行编译:
#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;
}
Why is this? 为什么是这样?
When you call push_back(of)
on a vector
, it tries to add a copy of the object of
to the vector. 在
vector
上调用push_back(of)
时,它将尝试将对象of
副本添加到vector上。 (C++ loves making copies of things). (C ++喜欢复制事物)。 In this case, you're trying to copy an
ofstream
, which isn't permitted. 在这种情况下,您尝试复制一个
ofstream
,这是不允许的。 Intuitively, it's not clear what it would mean to have a copy of an ofstream
, so the spec prohibits it. 直觉上,尚不清楚拥有
ofstream
的副本意味着什么,因此规范禁止使用它。
On the other hand, suppose you have a vector
of ofstream*
s. 另一方面,假设您有一个
vector
ofstream*
。 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. 现在,如果你尝试
push_back
一个指向ofstream
,那么C ++解释这意味着你应该把指针的一个拷贝到vector
,这没关系,因为指针很容易被周围复制。
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.
C ++最近引入了移动语义的想法,您可以将文件流移动到向量中,而不是尝试将文件流复制到向量中。 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; 这样做了以后,变量
of
将不参考了原来的文件流; it'll instead just have some dummy value. 相反,它将仅具有一些虚拟值。 However, the vector will now effectively contain the stream that used to be stored in
of
. 但是,向量现在将有效地包含以前存储在
of
的流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.