Difference between returning a const reference and rvalue reference

后端 未结 2 1233
旧时难觅i
旧时难觅i 2021-02-06 08:15

If I\'m not wrong, I think that both a const reference and a rvalue reference can bind to a rvalue. Is there any practical difference between a function that returns the former

2条回答
  •  你的背包
    2021-02-06 08:46

    Is there any practical difference between a function that returns the former and a function that returns the latter?

    The question seems to be ill-formed. A function that returns a constant lvalue-reference provides access to an object only for reading, while a function that returns an rvalue-reference provides access for moving which means that the caller can take the contents of the referred object and move it to a different object. They are not comparable by any means.

    In both cases, the references must point to an object whose lifetime spans beyond the end of the function that is returning it, as otherwise the caller will trip with undefined behavior on using that reference.

提交回复
热议问题