[英]C++ - overloaded assignment operator memory leaks
我有一個可與對象副本配合使用的類方法(准確地說,是* this)。 泄漏發生在過載的賦值運算符中-無論如何,這就是Visual Leak Detector所說的。 我正在做的工作是復制,如果完成的工作令人滿意,我可以將新創建的對象復制回去。 我還實現了自定義析構函數,復制構造函數和賦值運算符,因為顯然動態分配內存會出現問題。 我對C ++的經驗非常有限,因此代碼中可能包含一些邪惡的東西。
如果需要,我將提供更多信息。
問題方法:
bool Grid::SurroundShipSquares(int top, int bottom, int left, int right)
{
// copying itself
Grid gridCopy(*this);
Square** squaresCopy = gridCopy.GetSquares();
for (int i = top; i <= bottom; ++i)
{
for (int j = left; j <= right; ++j)
{
if (squaresCopy[i][j].GetState() != SquareState::Vacant)
return false;
(squaresCopy[i][j]).SetState(SquareState::Unoccupiable);
}
}
// the problem occurs here
*this = gridCopy;
return true;
}
復制構造函數:
Grid::Grid(const Grid& source)
{
_position = source._position;
_size = source._size;
int dimensions = static_cast<int>(_size);
_squares = new Square*[dimensions];
for (int i = 0; i < dimensions; ++i)
{
_squares[i] = new Square[dimensions];
for (int j = 0; j < dimensions; ++j)
{
_squares[i][j] = source._squares[i][j];
}
}
}
分配運算符:
Grid& Grid::operator=(const Grid& source)
{
if (this == &source)
return *this;
_position = source._position;
_size = source._size;
int dimensions = static_cast<int>(_size);
_squares = new Square*[dimensions];
for (int i = 0; i < dimensions; ++i)
{
_squares[i] = new Square[dimensions];
for (int j = 0; j < dimensions; ++j)
{
_squares[i][j] = source._squares[i][j];
}
}
return *this;
}
析構函數:
Grid::~Grid()
{
int dimensions = static_cast<int>(_size);
for (int i = 0; i < dimensions; ++i)
{
delete[] _squares[i];
}
delete[] _squares;
}
代碼的問題是您手動管理所有資源。 這是非常不安全的,並且很難正確地進行操作,這兩個現有答案都是錯誤的。
使用std::vector
。 此類將自動為您管理所有內存,使您不必自己做。 這將大大簡化您的代碼,並使其正確。
同樣,自我分配檢查是一種古老的反模式。 不包括自我分配支票。 如果您的賦值運算符(在大多數情況下,您實際上不需要真正使用基於std::vector
的內存管理編寫自己的代碼)不能在沒有特殊情況的情況下處理自賦值,則它會被破壞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.