我意识到这是错误的(我的编译器是这么说的!):在不引起内存泄漏的情况下返回对本地/临时对象的引用?
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