[英]Why am I getting 'vector subscript out of range'?
我正在嘗試做最簡單的事情,但出現“向量下標超出范圍”錯誤! 我不明白為什么會這樣,因為我檢查以確保不會發生這種情況。 它發生的唯一功能是addTexture
。
#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;
};
#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.