c++ - Copying "this" pointer to a buffer -
i need copy address of this pointer buffer , re-typecast elsewhere. aware can it, if outside class. but,here need use member function given in sample code provided here:
#include <iostream> #include <cstring> class myclass { public: myclass(const int & i) { id = i; } ~myclass() { } void getaddress(char* address) { memcpy(address, this, sizeof(this)); } void print() const { std::cout<<" id: "<<id<<std::endl; } private: int id; }; int main() { myclass myclass(100); std::cout<<"myclass: "<<&myclass<<std::endl; myclass.print(); // need copy address buffer, sepcifically using function follows , retrieve later char tmp[128]; myclass.getaddress(tmp); // retreiving pointer myclass* myclassptr = (myclass*) tmp; std::cout<<"myclassptr: "<<myclassptr<<std::endl; myclassptr->print(); return 0; } my output:
myclass: 0x7fff22d369e0 id: 100 myclassptr: 0x7fff22d369f0 id: 100 as can see 2 addresses different. however, both function printing id correctly. wonder how happens! need correct method.
correct version of getaddress():
void getaddress(char* address) { const myclass* tmp = this; memcpy(address, &tmp, sizeof(this)); } update:
// retreiving pointer // myclass* myclassptr = (myclass*) tmp; - wrong myclass* myclassptr = *( (myclass**) tmp );
Comments
Post a Comment