fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct HasAResource
  5. {
  6. int* arr;
  7.  
  8. HasAResource(int size):
  9. arr(new int [size])
  10. {
  11. cout << "size constructor: " << this << endl;
  12. }
  13.  
  14. HasAResource(const HasAResource& other) = delete;
  15. HasAResource& operator=(const HasAResource& other) = delete;
  16.  
  17. HasAResource(HasAResource&& other):
  18. arr(nullptr)
  19. {
  20. arr = other.arr;
  21. other.arr = nullptr;
  22. cout << "move constructor: " << this << endl;
  23. }
  24.  
  25. HasAResource& operator=(HasAResource&& other)
  26. {
  27. cout << "move assignment: from " << &other << " to " << this << endl;
  28. if (this != &other)
  29. {
  30. delete[] arr;
  31. arr = other.arr;
  32. other.arr = nullptr;
  33. }
  34. return *this;
  35. }
  36.  
  37. ~HasAResource()
  38. {
  39. cout << "destructor: " << this << endl;
  40. delete[] arr;
  41. }
  42.  
  43. void doStuff()
  44. {
  45. cout << "doStuff: " << this << endl;
  46. // do stuff...
  47. }
  48.  
  49. static HasAResource doStuff(int size)
  50. {
  51. cout << "doStuff(int)" << endl;
  52. HasAResource x(size);
  53. x.doStuff();
  54. return x;
  55. }
  56. };
  57.  
  58. int main()
  59. {
  60. HasAResource x = HasAResource::doStuff(42);
  61. return 0;
  62. }
Success #stdin #stdout 0s 5452KB
stdin
Standard input is empty
stdout
doStuff(int)
size constructor: 0x7ffefee4bfb0
doStuff: 0x7ffefee4bfb0
destructor: 0x7ffefee4bfb0