Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscripting a reference to const

I'm here looking at some C++ code and am not understanding something. It is irrelevant but it comes from a YARP (robot middleware) tutorial which goes with the documentation.

virtual void getHeader(const Bytes& header) 
{
  const char *target = "HUMANITY";
  for (int i=0; i<8 && i<header.length(); i++) 
  {
    header.get()[i] = target[i]; 
  }
}

Now, header is a reference to const and thus cannot be modified within this function. get is called on it, its prototype is char *get() const;. How can header.get() be subscripted and modified ? The program compiles fine. I may have not understood what happens here but I'm basing myself on what I've read in C++ Primer...

I would very much appreciate a little clarification!

Have a nice day,

like image 325
technimage Avatar asked Nov 12 '22 05:11

technimage


1 Answers

char *get() const;

The right hand const means "this member doesn't alter anything in the class that's not mutable", and it's honoring that - it isn't changing anything. The implementation is probably something like this:

char *Bytes::get() const
{
    return const_cast<char *>(m_bytes);
}

The pointer that is being returned, however, is a simple "char*". Think of it this way:

(header.get())[i] = target[i];
// or
char* p = header.get();
p[i] = target[i];
like image 79
kfsone Avatar answered Nov 14 '22 22:11

kfsone