简体   繁体   English

Memcpy和const正确性

[英]Memcpy and const correctness

When using cppcheck on my code it indicated a function could be made const. 在我的代码上使用cppcheck时,表明可以将函数设为const。 Cppcheck seems to be correct but I found the memcpy in the code strange. Cppcheck似乎是正确的,但是我发现代码中的memcpy很奇怪。

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. 据我了解,memcpy将间接写入_buffer,因此该函数不是const。 However even when using _buffer directly the compiler still compiles the code without an error. 但是,即使直接使用_buffer,编译器仍然可以正确编译代码。

Why does the compiler not generate an error here? 为什么编译器在这里不生成错误?

There are two different places where const can be used with pointers. const可在两个不同的地方与指针一起使用。

 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. 使对象成为const会使指针类型的成员成为第二种意义上的const ,而从第一种意义上来说则不会。 The current object ( *this ) is const in a const member function. 当前对象( *this )被const在一个const成员函数。

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: 如果您还需要将指向的数据也变成const ,则可以将指针包装const深度传播的自定义类中:

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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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