开发者

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

This question already has answers here: Can a local variable's memory be accessed outside its scope? (20 answers) Closed 6 years ago.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜