所以我正在编写一些代码,我有这样的代码:
class Box
{
private:
float x, y, w, h;
public:
//...
Rectangle & GetRect( void ) const
{
return Rectangle( x, y, w, h );
}
};
然后在一些代码中:
Rectangle rect = theBox.GetRect();
Which worked in my debug build, but in release there were "issues" returning that Rectangle by reference -- I basically got an uninitialized rectangle. The Rectangle class has an = operator and a copy constructor. Without getting into why this broke, I'm actually more interested in the correct way to return a (new) object by reference for the purpose of assigning copying to a variable. Am I just being silly? Should it not be done? I know I can return a pointer and then dereference on assignment, but I'd rather not. Some part of me feels like returning by value would result in redundant copying of the object -- does the compiler figure that out and optimize it?
这似乎是一个微不足道的问题。经过多年的 C++ 编码,我不知道这一点,我感到几乎尴尬,所以希望有人能为我解决这个问题。 :)
您无法返回对堆栈上临时对象的引用。您有三个选择:
- 按值返回
- 通过指针通过引用返回到您使用 new 运算符在堆上创建的内容。
- 通过引用返回您通过引用收到的参数。 [编辑:感谢@harshath.jr 指出了这一点]
请注意,当您按值返回(如下面的代码所示)时,编译器应优化分配以避免复制 - 即,它将通过将 create+assign+copy 优化为 create 来创建单个矩形(矩形)。仅当您从函数返回时创建新对象时,这才有效。
Rectangle GetRect( void ) const
{
return Rectangle( x, y, w, h );
}
Rectangle rect = theBox.GetRect();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)