Created
May 8, 2014 06:09
-
-
Save l1fe/75965f69962222ae63ad to your computer and use it in GitHub Desktop.
This-pointer change
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <cassert> | |
| class MyClass { | |
| public: | |
| MyClass() : | |
| magic_number_(MAGIC_NUMBER ^ (size_t)this) | |
| { | |
| // Do nothing | |
| } | |
| bool isValid() { | |
| return magic_number_ == (MAGIC_NUMBER ^ ((size_t) this)); | |
| } | |
| void foo() { | |
| assert(isValid()); | |
| std::cout << "Everything is ok!" << std::endl; | |
| } | |
| MyClass* getThis() { | |
| return this; | |
| } | |
| private: | |
| enum { MAGIC_NUMBER = 0xcafed00d }; | |
| const unsigned long magic_number_; | |
| }; | |
| int main() { | |
| char* buffer = new char[sizeof(MyClass)]; | |
| std::cout << "Buffer adress: " << (size_t)buffer << std::endl; | |
| MyClass* x = new MyClass; | |
| std::cout << "Class adress: " << (size_t)(x->getThis()) << std::endl; | |
| std::cout << "Moving class to buffer" << std::endl; | |
| memmove(buffer, x, sizeof(MyClass)); | |
| std::cout << "Now class adress: " << (size_t)(reinterpret_cast<MyClass*>(buffer)->getThis()) << std::endl; | |
| reinterpret_cast<MyClass*>(buffer)->foo(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is this about ?