dereferencing a pointer when passing by reference

前端 未结 3 1352
忘了有多久
忘了有多久 2020-12-02 15:46

what happens when you dereference a pointer when passing by reference to a function?

Here is a simple example

int& returnSame( int &example )         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 16:05

    Dereferencing the pointer doesn't create a copy; it creates an lvalue that refers to the pointer's target. This can be bound to the lvalue reference argument, and so the function receives a reference to the object that the pointer points to, and returns a reference to the same. This behaviour is well-defined, and no temporary object is involved.

    If it took the argument by value, then that would create a local copy, and returning a reference to that would be bad, giving undefined behaviour if it were accessed.

提交回复
热议问题