Returning a reference to a local/temprorary object without causing a memory leak? [duplicate]
I realize this is wrong (my compiler says so!):
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())));
Poin开发者_开发知识库t 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);
}
What would be the correct way to return the calculated rectangle without causing a memory leak? Defining the rectangle as Rectangle* result = new Rectangle(topLeft, bottomRight) then returning the dereferenced pointer works but just seems...wrong. Any suggestions?
Either return by value:
Rectangle Rectangle::Overlap(const Rectangle& rectangle);
which does not require to change your function body, or add an additional parameter to return the result:
void Rectangle::Overlap(const Rectangle& rectangle, Rectangle& out);
and assign the result to the out parameter.
Just change the return type to Rectangle
(sans the reference).
Just return a Rectangle instead of a reference to one.
Make the return type a non-reference (value). Then the returned value will be fine, using the implicit copy-constructor...
精彩评论