سؤال

a) Are X1 and X2 below equivalent? If not, how should the explicit reinterpret/const casting be done?

 void some_legacy_function(const void* arg) {
    char** X1 = (char**) arg;
    char** X2 = reinterpret_cast<char**>(const_cast<void*>(arg)  ); 
    /* not surprisingly, indexing into X1 randomly crashes in release build */
 }

b) This cast seems quite strange to me, is it actually 100% legal under some circumstances?

هل كانت مفيدة؟

المحلول

a) The first line is equivalent to static_cast<char**>(const_cast<void*>(arg)), I believe. Not that it makes any difference.

b) Well, it is legal if arg actually does point to an array of char*. If one reinterpret_casts a T* pointer to U* pointer (for arbitrary types T and U, related or otherwise) and back to T*, one is guaranteed to get the original value back. So yes, one can construct an example where this code would work. It doesn't mean the function is well designed, of course.

نصائح أخرى

Yes they are basically the same except the c++ style cast shows the reader of the code that you are doing some weird stuff while its harder to notice with the c style.

Its legal yet as always its highly suspect when a const incoming parameter is being cast as non const.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top