c++ - 为什么我可以有一个 std::vector<std::ofstream*> 但不能有一个 std::vector<std::ofstream> ?

标签 c++ pointers vector ofstream

我有以下测试代码,其中有一个参数fS,它是ofstreams的容器:

    #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 中 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 中的流。

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

相关文章:

c++ - 如何通过本身是类成员的指针调用成员函数

c - 关于指针的简单问题以及如何在 C 中初始化数组

java - 迭代器或枚举,我应该使用什么?

go - 我如何获取数组元素的地址,该数组元素是结构的元素,该结构是指针

c++ - 用迭代器计算矩阵 vector<vector<double>> 的列和?

c++ - 如何将表示二进制的 int vector 转换为表示十进制数的 int vector ? C++

c++ - 有效地复制/乘法树

c++ - 在 C++ 中对结构进行排序

c++ - 如何从 spirit 语义规则绑定(bind)/调用存储在 fusion::vector 中的 boost::function?

c++ - C++中的指针数组和指向数组的指针