Casting from string to void * and vice versa

can I re-map an object of class STL from void *?

#include <string> void func(void *d) { std::string &s = reinterpret_cast<std::string&>(d); } int main() { std::string s = "Hi"; func(reinterpret_cast<void*>(&s)); } 
+4
source share
4 answers

Use static_cast to convert void pointers back to other pointers, just revert them back to the same type that was originally used. No conversion is required to convert to a void pointer.

This works for any type of pointer, including type pointers from stdlib. (Technically, any pointer to an object type, but this is what is meant by "pointers", other types of pointers, such as pointers to data elements, require qualification.)

 void func(void *d) { std::string &s = *static_cast<std::string*>(d); // It is more common to make sa pointer too, but I kept the reference // that you have. } int main() { std::string s = "Hi"; func(&s); return 0; } 
+10
source

I rewrote the following entry,

 #include<string> void func(void *d) { std::string *x = static_cast<std::string*>(d); /* since, d is pointer to address, it should be casted back to pointer Note: no reinterpretation is required when casting from void* */ } int main() { std::string s = "Hi"; func(&s); //implicit converssion, no cast required } 
+3
source

You do not have to compile the code. The change

 std::string &s = reinterpret_cast<std::string&>(d); 

to

 std::string *s = static_cast<std::string*>(d); 

EDIT: Updated code. Use static_cast instead of reinterpret_cast

+1
source

Yes, it is possible, but you are trying to make from a pointer to void * , and then to a link. The reinterpret_cast operator allows you to return only the same type that you started working with. Try instead:

 void func(void *d) { std::string &s = *reinterpret_cast<std::string*>(d); } 
0
source

Source: https://habr.com/ru/post/1337134/


All Articles