开发者

Why creating an lvalue is one of the benefits of returning a reference in C++?

I am reading some C++ text at the address: https://cs.senecac.on.ca/~chris.szalwinski/archives/oop244.071/content/custo_p.html. In the section RETURNING A REFERENCE, the author wrote:

" Returning a reference from a function has two intrinsic benefits:

"

I can understand the first benefit (efficiency), but do not understand why is the second one.

As the author explained, I can understand that what is lvalue, but I do not understand what is the relationship between the lvalue and returning a reference from a function so that lvalue becomes a benefit?


That simply means that you can assign something to the result of the function. Consider this example:

int& foo() {
  static int x;
  return x;
}

void bar() {
  foo() = 42;
}

Instead of int, this works with class objects as well, of course. The point is that by returning a reference to x the caller can directly assign the locally scoped variable in foo. This is what the author means by saying that a reference return value "creates an lvalue".

By the way, the example actually has an application, as it solves the static initialisation order fiasco for more complex types than int.

Edit

As for the "benefit", there are several ways to interpret this. Either it is a way of making your code more readable (as opposed to the same functionality implemented with pointers) or that you can use operations that can only be applied to an lvalue, which would not be possible if you would not return a reference/pointer but received an argument:

struct X {
  int a;
  int b;
};
class Y_withoutRefs {
  private:
    X x;
  public:
    void setXa(int a) {
      x.a = a;
    }
    int getXa() {
      return x.a;
    }
    void setXb(int b) {
      x.b = b;
    }
    int getXb() {
      return x.b;
    }
};
class Y_withRefs {
  private:
    X x;
  public:
    X& getX() {
      return x;
    }
};

void dosmth() {
  Y_withoutRefs ywo;
  Y_withRefs yw;
  ywo.setXa(50+ywo.getXa());
  yw.getX() += 50;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜