C++ Return value, reference, const reference

前端 未结 5 1511
花落未央
花落未央 2020-12-12 14:06

Can you explain to me the difference between returning value, reference to value, and const reference to value?

Value:

Vector2D oper         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 14:57

    The difference between return-by-value and return-by-reference takes effect during run-time:

    When you return an object by-value, the copy-constructor is called, and a temporary instance is created on the stack.

    When you return an object by-reference, all the above does not take place, leading to improved performance.


    The difference between return-by-reference and return-by-constant-reference has no run-time effect, and is simply there to protect you from writing erroneous code.

    For example, with Vector2D& operator += (const Vector2D& vector), you can do:

    (x+=y)++ or (x+=y).func() where func is a non-const function in class Vector2D.

    But with const Vector2D& operator += (const Vector2D& vector), the compiler will generate an error for any such similar attempt.

提交回复
热议问题