-1

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?

orbitcowboy
  • 1,190
  • 9
  • 22
refro
  • 209
  • 1
  • 7
  • 4
    Hard to tell if you don't post the function signature and where cppcheck wants you to place the `const`. Please create a [MCVE]. – Vittorio Romeo Apr 20 '17 at 09:06
  • 7
    It's modifying things pointed by `_buffer`, not `_buffer` itself; then it could be `const` function. – songyuanyao Apr 20 '17 at 09:06
  • 3
    You are using a C-style cast, which basically means you know better than your compiler and it needs to shut up and do what you are telling it. If you want your tools to typecheck your code for you, consider not using C-style casts. – n. 'pronouns' m. Apr 20 '17 at 09:34

1 Answers1

2

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;
};
n. 'pronouns' m.
  • 95,181
  • 13
  • 111
  • 206