2010-12-17 31 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

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

相关问题