Advertisement
tinyevil

Untitled

Jul 29th, 2018
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. #include <vector>
  2. #include <memory>
  3. #include <iostream>
  4. #include <cstdlib>
  5. #include <cstring>
  6. using namespace std;
  7.  
  8. class Foo {
  9. public:
  10.     Foo(int size)
  11.         : size(size)
  12.         , arr(new int[size]) {
  13.         for ( int i = 0; i < size; i++ ){
  14.             arr[i] = i;
  15.         }
  16.     }
  17.  
  18.     Foo(const Foo& foo)
  19.         : size(foo.size) {
  20.  
  21.         foo.foo->print();
  22.        
  23.         arr = new int[size];
  24.         unsafe { memcpy(arr, foo.arr, sizeof(int) * size); }
  25.     }
  26.  
  27.     ~Foo(){
  28.         unsafe { delete[] arr; }
  29.     }
  30.  
  31.     void print(){
  32.         for (int i = 0; i < size; i++) {
  33.             unsafe { std::cout << arr[i] << " "; }
  34.         }
  35.         std::cout << "\n";
  36.     }
  37.  
  38.     Foo& operator=(const Foo& foo) {
  39.         this->~Foo();
  40.         new(this)Foo(foo);
  41.         return *this;
  42.     }
  43.  
  44.     void set_other(const shared_ptr<Foo>& other) {
  45.         foo = other;
  46.     }
  47. private:
  48.     int size;
  49.     int* arr;
  50.     shared_ptr<Foo> foo;
  51. };
  52.  
  53. int main() {
  54.     shared_ptr<Foo> a = make_shared<Foo>(10);
  55.     shared_ptr<Foo> b = make_shared<Foo>(20);
  56.  
  57.     b->set_other(a);
  58.    
  59.     a->print();
  60.     b->print();
  61.  
  62.     *a = *b;
  63.  
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement