Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. struct Obj
  2. {
  3.     Obj() : mem(nullptr) {}
  4.    
  5.     ~Obj()
  6.     {
  7.         if(mem)
  8.         {
  9.             cout << "freeing" << endl;
  10.             free(mem);
  11.         }
  12.     }
  13.    
  14.     Obj(Obj&& other) : mem(other.mem)
  15.     {
  16.         cout << "1" << endl;
  17.         other.mem = nullptr;
  18.     }
  19.    
  20.     Obj& operator=(Obj&& other)
  21.     {
  22.         cout << "2" << endl;
  23.         if(this != &other)
  24.         {
  25.             mem = other.mem;
  26.             other.mem = nullptr;
  27.         }
  28.         return *this;        
  29.     }
  30.    
  31.     Obj(const Obj& other) : mem(other.mem)
  32.     {
  33.         cout << "3" << endl;
  34. //         other.mem = nullptr;
  35.     }
  36.  
  37.     static Obj Create()
  38.     {
  39.         Obj o;
  40.         o.mem = malloc(4 * sizeof(int));
  41.         o.set();
  42.        
  43.         return o;
  44.     }
  45.    
  46.     void set()
  47.     {
  48.         int* ptr = reinterpret_cast<int*>(mem);
  49.         *(ptr) = 1;
  50.         *(ptr + 1) = 2;
  51.         *(ptr + 2) = 3;
  52.         *(ptr + 3) = 4;
  53.     }
  54.    
  55.     void print()
  56.     {
  57.         int* ptr = reinterpret_cast<int*>(mem);
  58.         for(int i = 0; i < 4; ++i)
  59.             cout << *(ptr + i) << " ";
  60.         cout << endl;
  61.     }
  62.    
  63.     void* mem;
  64. };
  65.  
  66. Obj Create1()
  67. {
  68.     Obj o;
  69.     o.mem = malloc(4 * sizeof(int));
  70.     o.set();
  71.  
  72.     return o;
  73. }
  74.  
  75. int main()
  76. {
  77.     Obj o(Create1());
  78.  
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement