返回对本地/临时对象的引用而不导致内存泄漏?
我意识到这是错误的(我的编译器是这么说的!):
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);
}
返回计算出的矩形而不导致内存泄漏的正确方法是什么?将矩形定义为 矩形* 结果 = 新矩形(topLeft,bottomRight) 然后返回取消引用的指针可以工作,但似乎......错误。有什么建议吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要么按值返回:
不需要更改函数体,要么添加一个附加参数来返回结果:
并将结果分配给 out 参数。
Either return by value:
which does not require to change your function body, or add an additional parameter to return the result:
and assign the result to the out parameter.
只需将返回类型更改为 Rectangle(无引用)即可。
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...