1

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?

Casey
  • 10,297
  • 11
  • 59
  • 88
  • This isn't a memory leak. On the contrary, you are freeing memory (a temporary variable that is created when you call Rectangle() constructor) before you ever get a chance to actually access it. See hkasier's answer for workarounds. – Sergei Tachenov Dec 17 '10 at 06:25

4 Answers4

4

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.

hkaiser
  • 11,403
  • 1
  • 30
  • 35
3

Make the return type a non-reference (value). Then the returned value will be fine, using the implicit copy-constructor...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ianmac45
  • 2,258
  • 2
  • 19
  • 15
3

Just change the return type to Rectangle (sans the reference).

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
3

Just return a Rectangle instead of a reference to one.

Anon.
  • 58,739
  • 8
  • 81
  • 86