【问题标题】:Returning a reference to a local/temprorary object without causing a memory leak? [duplicate]返回对本地/临时对象的引用而不导致内存泄漏? [复制]
【发布时间】:2010-12-17 01:17:48
【问题描述】:

我意识到这是错误的(我的编译器这么说!):

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

在不导致内存泄漏的情况下返回计算出的矩形的正确方法是什么?将矩形定义为 Rectangle* result = new Rectangle(topLeft, bottomRight) 然后返回取消引用的指针有效,但似乎......错误。有什么建议吗?

【问题讨论】:

  • 这不是内存泄漏。相反,在您有机会实际访问它之前,您正在释放内存(调用 Rectangle() 构造函数时创建的临时变量)。有关解决方法,请参阅 hkasier 的答案。

标签: c++ overlap allegro


【解决方案1】:

按值返回:

Rectangle Rectangle::Overlap(const Rectangle& rectangle);

不需要改变你的函数体,或者添加一个额外的参数来返回结果:

void Rectangle::Overlap(const Rectangle& rectangle, Rectangle& out);

并将结果分配给 out 参数。

【讨论】:

  • 或者在第二个示例中使用指针以 C 方式执行。有时它会提高可读性。
【解决方案2】:

只需将返回类型更改为Rectangle(没有引用)。

【讨论】:

    【解决方案3】:

    只返回一个 Rectangle 而不是对一个的引用。

    【讨论】:

      【解决方案4】:

      使返回类型成为非引用(值)。然后返回值就可以了,使用隐式复制构造函数...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-26
        • 1970-01-01
        • 2017-06-28
        • 1970-01-01
        • 1970-01-01
        • 2010-12-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多