Why does Visual C++ warn on implicit cast from const void ** to void * in C, but not in C++?

后端 未结 2 1320
天涯浪人
天涯浪人 2020-12-06 05:17

Summary

The C/C++ compiler in Microsoft Visual Studio gives warning C4090 when a C program tries to convert a pointer to pointer to const data (like <

相关标签:
2条回答
  • 2020-12-06 05:24

    Apparently this is simply a bug in VC++.

    If you declare const char **x; the result is a pointer to a "read-only" pointer to chars, and it's not itself a "read-only" pointer (I use the term "read-only" because const-ness term pushes the wrong concept that the character being pointed to is constant while this is false in general... const with references and pointers is a property of the reference or of the pointer and tells nothing about constness of the pointed-to or referenced data).

    Any read/write pointer can be converted to a void * and VC++ has no real reason to emit a warning when compiling that code, neither in C nor in C++ mode.

    Note that this is not formally a problem because the standard doesn't mandate which warnings should or should not be issued and therefore a compiler is free to emit warnings for perfectly valid code still remaining compliant. VC++ actually emits a plethora of those warnings for valid C++ code...

    0 讨论(0)
  • 2020-12-06 05:35

    Like 6502 says this seems to be a bug in the compiler. However, you also ask what you should do about it.

    My answer is that you should add an explicit cast to the free call, and then a comment explaining why it is needed. Bugs in the compiler do happen, use the easiest workaround and add a note such that it can be tested if the bug has been resolved later.

    Extra points for also reporting the bug to the compiler vendor.

    As for 1. It seems to be referring to implicitly casting a const T * to a void *, which should be a warning in C and an error in C++.

    0 讨论(0)
提交回复
热议问题