是一个函数,用于转换复制返回值的对象
Is a function to convert an object copying the return value?
在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);
除非我弄错了,这类似于返回值优化的典型实现方式。这让我们想到了其他评论者提出的观点,有可能编译器已经为你优化了副本。
相关文章:
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 转换运算符不适用于sleep_until
- 用于将C++代码转换为 Web 程序集的脚本未终止
- 为什么 openmp 的并行不适用于矢量化色彩空间转换?
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- Rcpp并行无匹配函数,用于调用"转换"
- 如何将我的小程序转换为用于项目的函数?
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- 用于 boost::p roperty_tree 的通用枚举转换器
- 用于从 ANSI 字符串转换为 std::basic_string <TCHAR>的正确函数声明
- 将 std::string 转换为 const char* 用于 printf 消耗
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 表达式模板玩具示例:用户定义的强制转换不适用于复杂类型
- C++实用程序,用于将长开关语句转换为封装开关案例阶梯的简洁函数调用
- 用户定义的转换不适用于可变参数函数参数?为什么不呢?
- 用于将笛卡尔 (x,y,z) 转换为圆柱坐标 (ρ,θ,z) 坐标 2D/3D 的代码
- 在 C++ 中,用于将大型 2D 数组转换为 1D 数组的内存分配
- 自动符号转换,用于对类等数学向量进行操作
- SSE2优化用于从RGB565转换为RGB888(无alpha通道)
- 用于初始化结构的 void 指针强制转换