C Question: (const void *) vs (void *)

后端 未结 2 423
独厮守ぢ
独厮守ぢ 2021-01-30 05:36

What\'s the difference between const void * and void *? Under what circumstances can a void pointer be cast to a const void pointer?

2条回答
  •  星月不相逢
    2021-01-30 06:19

    A const void * points to memory that should not be modified.

    A void * (non-const) points to memory that could be modified (but not via the void *; you'd have to cast it first).

    When you use memmove(), the source address is cast to const void *:

    void *memmove(void *dst, const void *src, size_t nbytes);
    

    That is an illustration when a void pointer can be cast to a constant void pointer. Basically, you can do it (convert to constant) at any time when you know you are not going to modify the memory that the pointer points at. This applies to any pointer - not just void pointers.

    Converting the other way (from a constant pointer to a non-constant pointer) is a much more dangerous exercise. There's no guarantee that the memory pointed at actually is modifiable; for example, a string literal can be stored in readonly (constant) memory, and if you lose the const-ness with a cast and try to modify the string, you will likely get a segmentation fault or its equivalent - your program will stop suddenly and not under your control. This is not a good thing. So, do not change pointers from constant to non-constant without being very sure it is actually OK to lie to your compiler. Be aware that compilers do not like being lied to and can get their own back, usually at the most inconvenient moment (such as when demonstrating your program to an important prospective client in front of your boss, your boss's boss, and your boss's boss's boss).

提交回复
热议问题