2010-12-17 30 views
1

我意識到這是錯誤的(我的編譯器是這麼說的!):在不引起內存泄漏的情況下返回對本地/臨時對象的引用?

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),然後返回解除引用的指針,但似乎...錯誤。有什麼建議麼?

+0

這不是內存泄漏。相反,在您有機會實際訪問它之前,您正在釋放內存(在調用Rectangle()構造函數時創建的臨時變量)。有關解決方法,請參閱hkasier的答案。 – 2010-12-17 06:25:53

回答

4

要麼返回的值:

Rectangle Rectangle::Overlap(const Rectangle& rectangle); 

不需要改變你的函數體,或者添加額外的參數,以返回結果:

void Rectangle::Overlap(const Rectangle& rectangle, Rectangle& out); 

和結果分配給了參數。

+0

或者在第二個示例中使用指針進行C方式。有時它會提高可讀性。 – 2010-12-17 06:27:14

3

使返回類型成爲非引用(值)。然後返回的值會很好,使用隱式的複製構造函數...

3

只需將返回類型更改爲Rectangle(無參考)。

3

只返回一個矩形而不是一個引用。

相關問題