Advertisement
Guest User

Untitled

a guest
May 14th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. class Vector
  5. {
  6. public:
  7.     Vector(int size) : sz(size){
  8.         elem = new double[sz];
  9.         for (int i = 0; i < sz; ++i)
  10.             elem[i] = i;
  11.     }
  12.  
  13.     Vector(const Vector& other) : sz(other.sz) {
  14.         elem = new double[sz];
  15.         for (int i = 0; i < sz; ++i)
  16.             elem[i] = other[i];
  17.     }
  18.  
  19.     Vector& operator=(const Vector& a)
  20.     {
  21.         std::cout << "Called Vector's copy assignment operator\n";
  22.         sz = a.sz;
  23.         double* p = new double[sz];
  24.         for (int i = 0; i < sz; ++i)
  25.             p[i] = a[i];
  26.         delete[] elem;
  27.         elem = p;
  28.         return *this;
  29.     }
  30.  
  31.     Vector(Vector&& other) {
  32.         elem = other.elem;
  33.         sz = other.sz;
  34.         other.elem = nullptr;
  35.         other.sz = 0;
  36.     }
  37.  
  38.     Vector& operator=(Vector&& other)
  39.     {
  40.         elem = other.elem;
  41.         sz = other.sz;
  42.         other.elem = nullptr;
  43.         other.sz = 0;
  44.         return *this;
  45.     }
  46.  
  47.     ~Vector() {
  48.         delete[] elem;
  49.     }
  50.  
  51.     Vector& operator+(const Vector& other)
  52.     {
  53.         for (int i = 0; i < sz; ++i)
  54.             elem[i] += other[i];
  55.         return *this;
  56.     }
  57.  
  58.     double &operator[](int pos) {
  59.         return elem[pos];
  60.     }
  61.  
  62.     const double &operator[](int pos) const {
  63.         return elem[pos];
  64.     }
  65.  
  66. private:
  67.     int sz;
  68.     double* elem;
  69. };
  70.  
  71. int main(int argc, char* argv[])
  72. {
  73.     Vector a(100000000);
  74.     Vector b(100000000);
  75.     Vector c(100000000);
  76.     Vector d = std::move(a+b+c);
  77.  
  78.     std::cout << "d[0] is " << d[0] << ", d[1] is " << d[1] << "\n";
  79.     std::cout << "Press a key to exit...\n";
  80.     std::cin.get();
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement