Search code examples
c++overlapallegro

Returning a reference to a local/temprorary object without causing a memory leak?


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())));

    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);
}

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?


Solution

  • 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.