Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the variable to which a C++ reference refers?

If I have this:

int a = 2; int b = 4; int &ref = a; 

How can I make ref refer to b after this code?

like image 488
Taru Avatar asked Oct 10 '11 13:10

Taru


People also ask

Can you change the address to which a reference refers?

A references is stored as a pointer, so you can always change where it points to as long as you know how to get its address.

How do I change the value of a reference variable in C++?

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 .

Can you reassign a reference?

Remember, once you initialize a reference, you cannot reassign it. A reference practically stands for an object. You cannot make it 'point' to a different object.

How do you assign a reference to a variable?

To assign reference to a variable, use the ref keyword. A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. Declare the reference parameters using the ref keyword.


2 Answers

This is not possible, and that's by design. References cannot be rebound.

like image 150
Björn Pollex Avatar answered Sep 23 '22 05:09

Björn Pollex


With C++11 there is the new(ish) std::reference_wrapper.

#include <functional>  int main() {   int a = 2;   int b = 4;   auto ref = std::ref(a);   //std::reference_wrapper<int> ref = std::ref(a); <- Or with the type specified   ref = std::ref(b); } 

This is also useful for storing references in containers.

like image 26
David C. Bishop Avatar answered Sep 25 '22 05:09

David C. Bishop