fork(2) download
  1. #include <iostream>
  2. #include <string>
  3. #include <memory>
  4.  
  5. using namespace std;
  6.  
  7. struct A
  8. {
  9. int x;
  10. std::string y;
  11. A(int x, std::string y) : x(x), y(y) {}
  12. A(A&& a) : x(std::move(a.x)), y(std::move(a.y)) {}
  13.  
  14. virtual const char* who() const { return "A"; }
  15. void show() const { std::cout << (void const*)this << " " << who() << " " << x << " [" << y << "]" << std::endl; }
  16. };
  17.  
  18. struct B : A
  19. {
  20. virtual const char* who() const { return "B"; }
  21. B(A&& a) : A(std::move(a)) {}
  22. };
  23.  
  24. template<class TO_T>
  25. inline TO_T* turn_A_to(A* a) {
  26. A temp(std::move(*a));
  27. a->~A();
  28. return new(a) B(std::move(temp));
  29. }
  30.  
  31.  
  32. int main()
  33. {
  34. A* pa = new A(123, "text");
  35. pa->show(); // 0xbfbefa58 A 123 [text]
  36. turn_A_to<B>(pa);
  37. pa->show(); // 0xbfbefa58 B 123 [text]
  38.  
  39. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
0x8c48020 A 123 [text]
0x8c48020 B 123 [text]