簡體   English   中英

為什么我的“向量下標超出范圍”?

[英]Why am I getting 'vector subscript out of range'?

我正在嘗試做最簡單的事情,但出現“向量下標超出范圍”錯誤! 我不明白為什么會這樣,因為我檢查以確保不會發生這種情況。 它發生的唯一功能是addTexture

TextureBank.h

#pragma once
#include "Disposable.h"
#include "Texture.h"
#include <vector>

class TextureBank: public Disposable
{
public:
    TextureBank();
    ~TextureBank();

    virtual void dispose();

    void addTexture(int location, Texture *tex);
    Texture *getTexture(int location);
private:
    std::vector<Texture*> textures;
};

TextureBank.cpp

#include "TextureBank.h"


TextureBank::TextureBank()
{
}

void TextureBank::dispose() {
    for each (Texture* tex in textures)
    {
        if (tex != nullptr) {
            tex->dispose();
        }
    }
}

void TextureBank::addTexture(int location, Texture *tex) {
    if (location > textures.size() - 1) {
        textures.resize(location + 1, nullptr);
    }
    textures[location] = tex;
}

Texture *TextureBank::getTexture(int location) {
    return textures[location];
}

TextureBank::~TextureBank()
{
    for each (Texture* tex in textures)
    {
        if (tex != nullptr) {
            delete tex;
        }
    }
}

罪魁禍首很可能是這樣的說法:

if (location > textures.size() - 1) {

textures.size()將是一個無符號整數類型,而location是一個int 在進行大於比較之前,將應用常規的算術轉換 ,這意味着location將轉換為相同的無符號整數類型。

如果textures為空並且location為零,則textures.size() - 1將導致該無符號類型的最大值,並且比較將得出false textures不會調整大小,您將嘗試訪問空vector的第零個元素,從而導致異常。

您可以通過將其修改為

if (location >= textures.size()) {

如果不能為負,也可以考慮將location為無符號類型; 並提高編譯器的警告級別,並注意警告!


您還應該考慮進行其他一些更改:

  • for each (Texture* tex in textures)都是一些非標准的編譯器擴展。 你應該根據各種替換此for可能的話- for(auto tex : textures)

  • 代替將原始擁有的指針存儲在textures ,可以考慮將類型更改為std::vector<std::unique_ptr<Texture>> 然后,您將不必顯式delete析構函數中的每個紋理。

  • 如果不能使用unique_ptr ,請確保您的類遵循“三規則”

  • 最好不要使用小型的RAII包裝器來處理需要內存管理的OpenGL類型,而不是使用Dispose()函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM