tomdodd4598

Untitled

Oct 27th, 2021
757
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <memory>
  3. #include <string>
  4. #include <utility>
  5.  
  6. struct Container {
  7.  
  8.     std::string str;
  9.  
  10.     Container(std::string&& s) : str{ std::move(s) } {
  11.         std::cout << "Constructor!\n";
  12.     }
  13.  
  14.     ~Container() {
  15.         // std::cout << "Destructor!\n";
  16.     }
  17.  
  18.     Container(const Container& oth) : str{ oth.str } {
  19.         std::cout << "Copy constructor!\n";
  20.     }
  21.  
  22.     Container(Container&& oth) noexcept : str{ std::move(oth.str) } {
  23.         std::cout << "Move constructor!\n";
  24.     }
  25.  
  26.     Container& operator=(const Container& oth) {
  27.         if (this != &oth) {
  28.             str = oth.str;
  29.         }
  30.         std::cout << "Copy assignment!\n";
  31.         return *this;
  32.     }
  33.  
  34.     Container& operator=(Container&& oth) noexcept {
  35.         if (this != &oth) {
  36.             str = std::move(oth.str);
  37.         }
  38.         std::cout << "Move assignment!\n";
  39.         return *this;
  40.     }
  41. };
  42.  
  43. void section(std::string&& s) {
  44.     std::cout << "\n" << std::string(s.length(), '~') << "\n" << s << "\n";
  45. }
  46.  
  47. int main()
  48. {
  49.     std::cout << "Values:\n";
  50.     Container a{ "test" };
  51.     Container b = a;
  52.     Container c{ a };
  53.     Container d{ Container{ "test" } };
  54.     Container e = Container{ "test" };
  55.  
  56.     std::cout << '\n';
  57.     a = b;
  58.     b = Container{ "test" };
  59.  
  60.     section("Lvalue references:");
  61.     Container& f = a;
  62.     Container& g = f;
  63.  
  64.     std::cout << '\n';
  65.     f = a;
  66.     g = f;
  67.  
  68.     section("Rvalue references:");
  69.     Container&& h = Container{ "test" };
  70.     Container&& i = std::move(c);
  71.  
  72.     std::cout << '\n';
  73.     h = Container{ "test" };
  74.     i = std::move(h);
  75.  
  76.     section("Values:");
  77.     Container j{ f };
  78.     Container k = g;
  79.     Container l{ h };
  80.     Container m = h;
  81.  
  82.     std::cout << '\n';
  83.     Container n{ std::move(h) };
  84.     Container o = std::move(h);
  85.     Container p{ std::move(d) };
  86.     Container q = std::move(e);
  87.     Container r{ std::move(f) };
  88.     Container s = std::move(g);
  89.  
  90.     std::cout << '\n';
  91.     n = f;
  92.     o = h;
  93.     p = std::move(f);
  94.     q = std::move(h);
  95. }
RAW Paste Data