fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <cstring>
  4.  
  5. struct A {
  6. std::string data;
  7. A(std::string v) :data(std::move(v)) {}
  8. void foo() {std::cout << data;}
  9. };
  10.  
  11. template<class T>
  12. struct reloc_ptr {
  13. template<class U>
  14. reloc_ptr(char*& base, int offset, U&& v) :base(&base), offset(offset) {new(get())T(std::forward<U>(v));}
  15. T* get() const {return (T*)(*base+offset);}
  16. T* operator->() const {return get();}
  17. void destroy() {get()->~T();}
  18. private:
  19. char** base;
  20. int offset;
  21. };
  22.  
  23. int main() {
  24. char* base = new char[1000];
  25. //construct
  26. reloc_ptr<A> clsA(base,4, "HI");
  27. //test
  28. clsA->foo();
  29. //move base
  30. char* other = new char[1000];
  31. memcpy(other, base, 1000);
  32. std::swap(base, other);
  33. delete[] other;
  34. //test
  35. clsA->foo();
  36. //cleanup
  37. clsA.destroy();
  38. delete[] base;
  39. }
  40.  
Success #stdin #stdout 0s 3028KB
stdin
Standard input is empty
stdout
HIHI