[英]Unexplained Behavior with std::vector
在逐步解決一些奇怪的分段錯誤導致的代碼中,我發現在將一個向量分配給另一個向量之后,接收向量會任意損壞。 以下是來自類的復制構造函數的代碼片段,該類的數據構造函數具有數據成員vector<Piece> *pieces
,這是一個動態分配的數組,其中包含Piece
類型的向量。
ClassName::ClassName(const Class &other) // copy constructor of class
{
...
for(SIDE_t s = 0; s < sides; s++)
{
pieces[s].reserve(other.pieces[s].size());
pieces[s] = other.pieces[s]; //vector is completely valid here
for(Uint8 p = 0; p < pieces[s].size(); p++)
{
//it continues validity throughout loop
if(other.pieces[s][p].getCell() != NULL)
pieces[s][p].setCell(cells + (other.pieces[s][p].getCell() - other.cells));
if(pieces[s][p].getCell() == NULL)
out.push_back(&pieces[s][p]);
}
if(other.flags[s] != NULL)
flags[s] = getPiece(other.flags[s]->getValue(), other.flags[s]->getSide());
// vector is invalid in scope of getPiece, which receives completely valid arguments
else
flags[s] = NULL;
}
}
Piece * const ClassName::getPiece(const Uint8 num, const SIDE_t s) const
{
return (num>nPieces || s>sides || num == 0)? NULL:&pieces[s][num-1];
// Right here during the member access function of pieces,
// it is clear that the vector was corrupted some how
}
在調試過程中從本質上講,我將踏入pieces[s]
成員訪問的功能。 在循環體中,顯而易見的是, m_start
具有有效的地址,然而,當它離開循環體,並呼吁索引操作pieces[s]
在getPiece
,M_START是NULL。 當m_start
有效時,在循環的最后一次迭代之間,以及在與循環體相同的索引運算符調用期間,在getPiece
中,沒有對pieces[s]
執行任何操作,而m_start
為NULL。 對於我濫用std :: vector或std :: vector中的錯誤的任何見解,將不勝感激。
在我看來,您在這里遇到訪問沖突:
return (num>nPieces || s>sides || num == 0)? NULL:&pieces[s][num-1];
首先(正如Petr指出的那樣),它應顯示為s>=sides
。
其次, s
這里是不一樣的s
在調用者。 因此, pieces[s]
可能尚未分配,並且是空向量。 要測試它使用
return (num>nPieces || s>=sides || num == 0)? NULL : &(pieces[s].at(num-1));
順便說一句,如果您只是使用所有這些本來可以避免的
std::vector<std::vector<Piece>>
並復制了整個內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.