c++solarissolaris-studio

Invalid addition of constness? Error: Cannot use char** to initialize const char**


Solaris Studio is generating the most puzzling of error messages.

158 char* inbufptr = buffer;
159 char* outbufptr = outbuf;
160 
161 const char** inbufptrpos = &inbufptr;

And the error message is:

line 161: Error: Cannot use char** to initialize const char**.

Why should it be a problem to add constness? I am stuck, please help me out...


 memory: [m y _ c h a r _ a r r a y | inbufptr | inbufptr_pos]
          ^                           ^
          | (1)                       | (2)
          inbufptr                    inbufptrpos

The pointer char* inbufptr points to the beginning of the array, and does not promise to keep anything constant.

Now if I now have a pointer char const **inbufptr_pos this type promises not the change the contents of the array, but I can still change where the pointer points to. If I do that I have not changed the array and I don't see a problem with that.


Solution

  • This is an age-old problem, whereby intuitively you think you can "add constness", but in fact adding constness indirectly violates const-correctness.

    The standard itself even has an example of it to help set people back on the correct path:

    #include <cassert>  
    
    int main() {  
      char* p = 0;  
    
      //char const** a = &p; // not allowed, but let's pretend it is  
      char const** a = (char const**)&p; // instead force the cast to compile  
    
      char const* orig = "original";  
      *a = orig; // type of *a is char const*, which is the type of orig, this is allowed  
    
      assert(p == orig); // oops! char* points to a char const*  
    }