Skip to content

Instantly share code, notes, and snippets.

@l1fe
Created May 8, 2014 06:09
Show Gist options
  • Select an option

  • Save l1fe/75965f69962222ae63ad to your computer and use it in GitHub Desktop.

Select an option

Save l1fe/75965f69962222ae63ad to your computer and use it in GitHub Desktop.
This-pointer change
#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;
}
@sarathsp06

Copy link
Copy Markdown

What is this about ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment