简体   繁体   中英

Having trouble maintaining const correctness with parameter passed by reference

I'm sure this has been asked before, but all the search results have const& questions.

I want to make sure the following method doesn't change the GuestNode passed to it, so I wanted to pass const GuestNode& guest , but g++ won't let that happen, because I'm assigning the &guest to pointers. Why does that happen? And how can I make sure the passed param stays as it was?

   void GuestList::Add(GuestNode& guest)
   {
      if ( first == 0 )
      {
         //first guest
         first = &guest;
      }
      else
      {
         //nth guest
         GuestNode *p = first;
         while ( p->next != 0 )
            p = p->next;
         p->next = &guest;
      }
      SetCount(GetCount() + 1);
   }

If you make guest a const GuestNode& , then &guest is a const GuestNode* . That is, it's a pointer to a const GuestNode . That makes sense, otherwise you'd be able to modify the const object through the non- const pointer to it. So if you're going to assign that pointer to first and/or p , you need to make sure that they are const GuestNode* s too.

If you need first , which I'm assuming is a member of GuestList , to be non- const , then you shouldn't be taking a const reference.

To demonstrate:

const int x = 5;
int* p = &x; // error: invalid conversion from ‘const int*’ to ‘int*’

Imagine if this weren't an error, I'd then be able to do *p = 10; to change the value of x , even though the object is supposed to be const .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM