Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dereferencing a pointer when passing by reference

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

Here is a simple example

int& returnSame( int &example ) { return example; }  int main() {   int inum = 3;   int *pinum = & inum;    std::cout << "inum: " <<  returnSame(*pinum) << std::endl;    return 0;            } 

Is there a temporary object produced?

like image 968
MWright Avatar asked Jul 05 '12 15:07

MWright


People also ask

Do you have to dereference a reference?

Once a reference is established to a variable, you cannot change the reference to reference another variable. To get the value pointed to by a pointer, you need to use the dereferencing operator * (e.g., if pNumber is a int pointer, *pNumber returns the value pointed to by pNumber .

What happens when you dereference a pointer?

Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer. The operator * is used to do this, and is called the dereferencing operator.

Can pointers be passed by reference?

You would want to pass a pointer by reference if you have a need to modify the pointer rather than the object that the pointer is pointing to. This is similar to why double pointers are used; using a reference to a pointer is slightly safer than using pointers.

What is the meaning of referencing and dereferencing of pointer in C?

I read about * referencing operator and & dereferencing operator; or that referencing means making a pointer point to a variable and dereferencing is accessing the value of the variable that the pointer points to.


1 Answers

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.

like image 75
Mike Seymour Avatar answered Sep 21 '22 06:09

Mike Seymour