有没有正确的方法在 C++ 中通过引用返回一个新的对象实例?

Is there a right way to return a new object instance by reference in C++?(有没有正确的方法在 C++ 中通过引用返回一个新的对象实例?)

本文介绍了有没有正确的方法在 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:

  1. 按值返回
  2. 通过指向您使用 new 运算符在堆上创建的内容的指针通过引用返回.
  3. 通过引用返回您收到的引用作为参数.

请注意,当您在下面的代码中按值返回时,编译器应优化赋值以避免复制 - 即它只会通过将 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++ 中通过引用返回一个新的对象实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:有没有正确的方法在 C++ 中通过引用返回一个新的对象实例?

基础教程推荐