C++ reinterpret_cast object to string and back -
i discovered reinterpret_cast in c++ , trying learn more it. wrote code:
struct human{ string name; char gender; int age; human(string n, char g, int a) : name(n), gender(g), age(a) {} }; int main() { human h("john", 'm', 26); char* s = reinterpret_cast<char*>(&h); human *hh = reinterpret_cast<human*>(s); cout << hh->name << " " << hh->gender << " " << hh->age << endl; }
it works pretty well, expected. want convert char *
std::string
, string human
object:
int main() { human h("john", 'm', 26); char* s = reinterpret_cast<char*>(&h); string str = s; human *hh = reinterpret_cast<human*>(&str); cout << hh->name << " " << hh->gender << " " << hh->age << endl; // prints wrong values }
does have idea overcome ?
thank you.
in second program when do
string str = s;
you create new object totally unrelated pointer s
. getting address str
give pointer str
, , not "string" contains.
also, using reinterpret_cast
way tell compiler "i know doing", , if don't know what's happening undoubtedly march territory of undefined behavior happen when try initialize str
"string" pointed s
, since it's not string.
Comments
Post a Comment