Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 向量容量太大了_C++_Visual C++_Stdvector - Fatal编程技术网

C++ 向量容量太大了

C++ 向量容量太大了,c++,visual-c++,stdvector,C++,Visual C++,Stdvector,所以我在vc++中遇到了std::vector的问题。在g++中,它工作得很好,但是在vc++中,在插入6个元素并调用构造函数后,容量值超过100000000,并且收缩到适合我的程序。我不知道这是什么原因,但我将发布原因代码: 此代码初始化向量: std::vector<unsigned> indices_rect { 0, 1, 2, 2, 3, 0 }; 在此之后,索引的容量仍然是6,就像大小一样。 但当我跳入Shaderfile的构造函数时,在执行第一行之前,

所以我在vc++中遇到了std::vector的问题。在g++中,它工作得很好,但是在vc++中,在插入6个元素并调用构造函数后,容量值超过100000000,并且收缩到适合我的程序。我不知道这是什么原因,但我将发布原因代码:

此代码初始化向量:

std::vector<unsigned> indices_rect {
    0, 1, 2,
    2, 3, 0
};
在此之后,索引的容量仍然是6,就像大小一样。 但当我跳入Shaderfile的构造函数时,在执行第一行之前,容量被设置为所述的大数值。这在下面的行中发生

engine::Shaderfile textured("../res/shaders/engine/textured.glsl", indices_rect);
我传递向量只是为了看看构造函数内部发生了什么。开头是这样的:

Shaderfile::Shaderfile(std::string path, const std::vector<unsigned>& v)
{
// Capacity gets set here
#ifdef _ENGINE_DEBUG
    _path = path;
#endif
    std::ifstream file;
    std::stringstream fs;
    file.exceptions(std::ifstream::badbit | std::ifstream::failbit);
...

但即使在线路_path=path之前,v的容量也超过100000000。如果有人知道问题可能是什么,请提供帮助。

问题是头文件中的预处理器条件。如果定义了makro,我将声明_path变量并在构造函数中使用相同的条件初始化它。一旦我删除了头文件中的条件,它就会工作

[Shaderfile.h]之前:

[Shaderfile.h]之后:


这个简单的改变使它起了作用。我在构造函数中仍然有预处理器条件。

我们需要知道。某些内容显然正在覆盖不应该覆盖的数据。什么在调用ShaderFile构造函数?纹理函数内部的东西?设置默认纹理有什么关系?@Quimby我真的不知道,什么是相关的。这些是从向量初始化到第一次遇到问题时调用的唯一几行代码。@程序员哦,对不起,我以为这是一个函数声明……当您打印std::coutf时会发生什么?根据您提供的信息,任何人几乎都无法帮上忙。很明显,您的程序中还有其他代码——可能是在您显示的代码之前执行的——可能会覆盖一些它不应该覆盖的内存。未定义行为的本质是任何事情都可能发生。有时“包含任何内容”的代码在一段时间内似乎什么都没有发生,然后一些不相关的代码爆炸出来。您必须通过反复试验、删除一些以前执行的代码、重建、重新启动程序并查看症状是否消失来反向工作。代码中的一些源模块似乎是在定义了_ENGINE_DEBUG的情况下编译的,而其他模块则是在没有它的情况下编译的。这会为ShaderFile类创建多个不同的定义,违反ODR。崩溃发生的原因是,当构造的对象没有_路径变量时,构造函数需要一个_路径变量,而在那里有一个数组变量,或者当有一个_路径时,构造函数不需要一个_路径。
Shaderfile::Shaderfile(std::string path, const std::vector<unsigned>& v)
{
// Capacity gets set here
#ifdef _ENGINE_DEBUG
    _path = path;
#endif
    std::ifstream file;
    std::stringstream fs;
    file.exceptions(std::ifstream::badbit | std::ifstream::failbit);
...
...
private:
#ifdef _ENGINE_DEBUG
    std::string _path;
#endif
    std::array<std::string, 4> _sources;
...
...
private:
    std::string _path;
    std::array<std::string, 4> _sources;
...