是一个函数,用于转换复制返回值的对象

Is a function to convert an object copying the return value?

本文关键字:转换 用于 复制 返回值 对象 函数 一个      更新时间:2023-10-16

在c++中,我有一个矩形参数进入函数。因为我保持我的系统抽象,我做了我自己的矩形类。我传递给它的函数(用于SFML图形库)使用它自己的RectangleShape对象。因此,我需要将矩形转换为RectangleShape。

我写了一个函数来做这个,但是我搞不清创建了什么对象,复制了谁,哪个最快。情况如下:

RectangleShape MyClass::ConvertRectangleToRectangleShape(const Rectangle& inRectangle)
{
    Vector2f size(inRectangle.GetWidth(), inRectangle.GetHeight());
    RectangleShape convertedRectangle(size);
    Vector2f position(inRectangle.GetPosition.GetX(), inRectangle.GetPosition.GetY());
    returnShape.SetPosition(position);
    return convertedRectangle;
}
void MyClass::DrawShape(const Rectangle& inRectangle)
{
    // Convert the shape
    RectangleShape convertedShape = ConvertRectangleToRectangleShape(inRectangle);
    // Rest of code here
}

如你所见,我的对象都不是指针。所以我不需要处理这个

返回的对象在堆栈上,但不是引用。当我返回它的时候它被复制了,对吧?这条线

return convertedRectangle;

它将矩形复制到第二个函数

中创建的变量中
RectangleShape convertedShape = ConvertRectangleToRectangleShape(inRectangle);

对吧?

我不能将它作为引用变量返回,因为一旦我离开函数的作用域,它就会被取消分配,对吗?

RectangleShape& MyClass::ConvertRectangleToRectangleShape(const Rectangle& inRectangle)

如果我不能返回它作为引用,并且我不想要一个副本,我是否只需要将代码粘贴到函数中?或者#define it?这里正确的方法是什么,或者我错在哪里?谢谢!

您的情况可以更简洁地表示为转换构造函数

class RectangleShape{
    ....
    RectangleShape(const Rectangle&);
    ...
};

那么你应该写

RectangleShape convertedShape = inRectangle;

它会像你期望的那样工作,没有任何不必要的复制或构造。

这将是与这种样式相似的

RectangleShape convertedShape;
convertedShape.InitFrom(inRectangle);

也不需要副本,因为它直接作为最终对象的方法调用。

克里斯建议(如果我理解正确的话)需要对class Rectangle进行更改,以允许它将自己转换为RectangleShape

class Rectangle{
    ....
    operator RectangleShape();
    ...
};

它将允许类似的优雅赋值代码,但我不确定他打算如何在没有副本的情况下从一个类转换到另一个,如果它们是不相关的类。

如果你不能修改RectangleShape,我能想到的最接近的是这样做。

InitRectangleShape(convertedShape, inRectangle);
....    
void InitRectangleShape(RectangleShape& convertedShape,const Rectangle& inRectangle);

除非我弄错了,这类似于返回值优化的典型实现方式。这让我们想到了其他评论者提出的观点,有可能编译器已经为你优化了副本。