Search code examples
c++static-code-analysiscppcheck

Memcpy and const correctness


When using cppcheck on my code it indicated a function could be made const. Cppcheck seems to be correct but I found the memcpy in the code strange.

Excerpt from the code:

 if ( (offset + size) <= _bufferSize )
        {
            char* _destPtr = (char*)_buffer + offset;
            memcpy(_destPtr, data, size);
            result = true;
        }

To my understanding the memcpy will indirectly write to _buffer so the function is not const. However even when using _buffer directly the compiler still compiles the code without an error.

Why does the compiler not generate an error here?


Solution

  • There are two different places where const can be used with pointers.

     const char * x;  // (1) data pointed by x is const
     char * const x;  // (2) x itself is const
    

    Making your object const makes its pointer-type members const in the second sense, never in the first sense. The current object (*this) is const in a const member function.

    If you need the pointed-to data become const too, you can wrap your pointers in a custom class that does deep propagation of constness:

    template <class T> class deep_const_ptr {
         // .... ctors, operator*, the usual stuff
         T* get() { return data; }
         const T* get() const { return data; }
      private:
         T* data;
    };