Advertisement
Savior

C++11: copy-and-swap with move semantics

Sep 29th, 2015
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. class Class {
  4.     int i;
  5.     char *p;
  6. public:
  7.     int geti() const { return i; }
  8.     void increment() { ++i; }
  9.     void decrement() { --i; }
  10.     void addr() const { std::cout << reinterpret_cast<void *>(p) << std::endl; }
  11.  
  12.     void swap(Class &other) { std::swap(i, other.i); std::swap(p, other.p); }
  13.  
  14.     // - Constructors
  15.     // --- Default
  16.     Class() : i(0), p(new char[10]) { std::cout << "Default ctor" << std::endl; }
  17.     Class(int val) : i(val), p(new char[10]) { std::cout << "ctor(int) with " << val << std::endl; }
  18.     // --- Copy
  19.     Class(const Class &other) : i(other.i), p(new char[10]) { std::cout << "Copy ctor" << std::endl; }
  20.     // --- Move
  21.     Class(Class &&other) : p(nullptr) { other.swap(*this); std::cout << "Move ctor" << std::endl; }
  22.  
  23.     // - Assignment
  24.     // --- Copy
  25.     Class &operator=(const Class &other) {
  26.         std::cout << "operator=(const Class&)" << std::endl;
  27.         if (this != &other)
  28.             Class(other).swap(*this);
  29.         return *this;
  30.     }
  31.     // --- Move
  32.     Class &operator=(Class &&other) {
  33.         std::cout << "operator=(Class&&)" << std::endl;
  34.         if (this != &other)
  35.             other.swap(*this);
  36.         return *this;
  37.     }
  38.     ~Class() { if(p) delete[] p; }
  39. };
  40.  
  41. void debug(const Class &x) {
  42.     std::cout << "i: " << x.geti() << std::endl;
  43.     std::cout << "p: ";
  44.     x.addr();
  45. }
  46.  
  47. int main() {
  48.     Class a(50);
  49.     debug(a);
  50.     std::cout << std::endl;
  51.  
  52.     a = (Class(423));
  53.     debug(a);
  54.     std::cout << std::endl;
  55.  
  56.     Class b(a);
  57.     b.increment();
  58.     a = b;
  59.     debug(a);
  60.     std::cout << std::endl;
  61.  
  62.     Class c(std::move(Class(121)));
  63.     debug(c);
  64. #ifdef _WIN32
  65.     system("pause");
  66. #endif
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement