我意識到這是錯誤的(我的編譯器是這麼說的!):在不引起內存泄漏的情況下返回對本地/臨時對象的引用?
Rectangle& Rectangle::Overlap(const Rectangle& rectangle) {
Point topLeft(__max(this->GetVerticies()[0]->GetX(), rectangle.GetVerticies()[0]->GetX()) - __min(this->GetVerticies()[0]->GetX() + this->GetWidth(), rectangle.GetVerticies()[0]->GetX() + rectangle.GetWidth()),
(__max(this->GetVerticies()[0]->GetY(), rectangle.GetVerticies()[0]->GetY()) - __min(this->GetVerticies()[0]->GetY() + this->GetHeight(), rectangle.GetVerticies()[0]->GetY() + rectangle.GetHeight())));
Point bottomRight(__min(this->GetVerticies()[0]->GetX() + this->GetWidth(), rectangle.GetVerticies()[0]->GetX() + rectangle.GetWidth()), topLeft.GetY() + __max(this->GetVerticies()[0]->GetY() + this->GetHeight(), rectangle.GetVerticies()[0]->GetY() + rectangle.GetHeight()));
return Rectangle(topLeft, bottomRight);
}
什麼是迴歸計算出的矩形,而不會造成內存泄漏的正確方法是什麼?將矩形定義爲Rectangle * result = new Rectangle(topLeft,bottomRight),然後返回解除引用的指針,但似乎...錯誤。有什麼建議麼?
這不是內存泄漏。相反,在您有機會實際訪問它之前,您正在釋放內存(在調用Rectangle()構造函數時創建的臨時變量)。有關解決方法,請參閱hkasier的答案。 – 2010-12-17 06:25:53