是否有正确的方法通过C ++中的引用返回一个新的对象实例? [英] Is there a right way to return a new object instance by reference in C++?
问题描述
所以我写了一些代码,我有这样的:
So I was writing some code, and I had something like this:
class Box
{
private:
float x, y, w, h;
public:
//...
Rectangle & GetRect( void ) const
{
return Rectangle( x, y, w, h );
}
};
稍后在一些代码中:
Rectangle rect = theBox.GetRect();
这在我的调试生成中有效,但在发布中有问题 - 我基本上有一个未初始化的矩形。 Rectangle类具有=运算符和复制构造函数。没有深入到为什么这会爆发,我实际上更感兴趣的是通过引用返回一个(新的)对象的正确方法,用于分配复制到一个变量。我只是傻吗?是不是应该做呢?我知道我可以返回一个指针,然后解除引用赋值,但我宁愿不。我的某些部分感觉像通过价值返回会导致对象的冗余复制 - 编译器计算出来并优化它吗?
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 ++编码,所以希望有人可以清除这对我来说。 :)
It seems like a trivial question. I feel almost embarrassed I don't know this after many years of C++ coding so hopefully someone can clear this up for me. :)
推荐答案
您不能返回对栈上临时对象的引用。您有三个选项:
You can't return a reference to a temporary object on the stack. You have three options:
- 按值返回
- 通过引用返回通过引用接收的参数作为参数。
请注意,编译器应该优化赋值以避免复制 - 即它将通过将create + assign + copy优化为create创建一个Rectangle(rect)。这只适用于从函数返回时创建新对象。
Note that when you return by value as in the code below, the compiler should optimize the assignment to avoid the copy - i.e. it will just create a single Rectangle (rect) by optimizing the create+assign+copy into a create. This only works when you create the new object when returning from the function.
Rectangle GetRect( void ) const
{
return Rectangle( x, y, w, h );
}
Rectangle rect = theBox.GetRect();
这篇关于是否有正确的方法通过C ++中的引用返回一个新的对象实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!