【发布时间】:2010-12-17 01:17:48
【问题描述】:
我意识到这是错误的(我的编译器这么说!):
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 的答案。