gpt4 book ai didi

c++ - 为什么我可以有一个 std::vector 而不是 std::vector

转载 作者:行者123 更新时间:2023-11-30 03:50:18 24 4
gpt4 key购买 nike

我有以下测试代码,其中有一个参数 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;
}

这根本无法编译。而当我将 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;
}

这是为什么?

最佳答案

当您在 vector 上调用 push_back(of) 时,它会尝试将对象 of 的拷贝添加到该 vector 。 (C++ 喜欢复制东西)。在这种情况下,您正在尝试复制 ofstream,这是不允许的。直觉上,不清楚拥有 ofstream 的拷贝意味着什么,因此规范禁止这样做。

另一方面,假设您有一个ofstream*vector。现在,如果您尝试 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 将不再引用原始文件流;它只会有一些虚拟值(value)。但是, vector 现在将有效地包含以前存储在 of 中的流。

关于c++ - 为什么我可以有一个 std::vector<std::ofstream*> 而不是 std::vector<std::ofstream>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31885704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com