Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

c++ - Why can I assign a new value to a reference, and how can I make a reference refer to something else?

I have couple of questions related to usage of references in C++.

  1. In the code shown below, how does it work and not give a error at line q = "world";?

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      char *p = "Hello";
      char* &q = p;
      cout <<p <<' '<<q <<"
    ";
      q = "World"; //Why is there no error on this line
      cout <<p <<' '<<q <<"
    ";
    }
    
    1. How can a reference q be reinitialized to something else?

    2. Isn't the string literal, p = "Hello", a constant or in read-only space? So if we do,

      q = "World";
      

      wouldn't the string at p which is supposed to be constant be changed?

  2. I have read about C++ reference type variables as they cannot be reinitialized or reassigned, since they are stored 'internally' as constant pointers. So a compiler would give a error.

    But how actually a reference variable can be reassigned?

    int i;
    
    int &j = i;
    
    int k;
    
    j = k; //This should be fine, but how we reassign to something else to make compiler flag an error?
    

    I am trying to get hold of this reference, and in that maybe missed some key things related, so these questions.

So any pointers to clear this up, would be useful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
    • a) It cannot, the line you quote doesn't change the reference q, it changes p.
    • b) No the literal is constant, but p is a pointer which points at a literal. The pointer can be changed, what is being pointed to cannot. q = "world"; makes the pointer p point to something else.
  1. You seem to think that this code

    int i;
    int &j = i;
    int k;
    j = k;
    

    is reassigning a reference, but it isn't. It's assigning the value of k to i, j still refers to i. I would guess that this is your major misunderstanding.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...