std :: vector容量太大了

问题描述 投票:-3回答:1

所以我遇到的vc ++中的std :: vector存在这个问题。在g ++中,它工作正常,但是在插入6个元素并调用构造函数后,在vc ++中,容量的值超过1000000000,而shrink_to_fit()会使我的程序崩溃。我不知道是什么导致这种情况,但我要发布原因的代码:

此代码初始化向量:

std::vector<unsigned> indices_rect {
    0, 1, 2,
    2, 3, 0
};

然后调用此静态函数,它只是为默认路径设置一个字符串:

engine::Texture::set_default_texture("../res/textures/engine/default_texture.jpg", engine::ImageType::JPG);

在此之后,indices_rect的容量仍然是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的容量也超过了1000000000.如果有人知道问题可能是什么,请帮忙。

c++ visual-c++ stdvector
1个回答
0
投票

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

[Shaderfile.h]之前:

...
private:
#ifdef _ENGINE_DEBUG
    std::string _path;
#endif
    std::array<std::string, 4> _sources;
...

[Shaderfile.h]之后:

...
private:
    std::string _path;
    std::array<std::string, 4> _sources;
...

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

© www.soinside.com 2019 - 2024. All rights reserved.