Guest User

Untitled

a guest
Mar 19th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. #include <iostream>
  2. #include <typeinfo>
  3.  
  4. static int test = 0;
  5. class A {
  6. public:
  7. A()
  8. : _a(0)
  9. {
  10. std::cout << __PRETTY_FUNCTION__ << std::endl;
  11. }
  12. explicit A(int a)
  13. : _a(a)
  14. {
  15. std::cout << __PRETTY_FUNCTION__ << std::endl;
  16. }
  17. A(const A& rhs)
  18. : _a(rhs._a)
  19. {
  20. std::cout << __PRETTY_FUNCTION__ << std::endl;
  21. }
  22. A(A&& rhs)
  23. : _a(std::move(rhs._a))
  24. {
  25. std::cout << __PRETTY_FUNCTION__ << std::endl;
  26. }
  27. ~A()
  28. {
  29. std::cout << __PRETTY_FUNCTION__ << std::endl;
  30. test++;
  31. }
  32.  
  33. int get() const { return _a; }
  34.  
  35. private:
  36. int _a;
  37. };
  38.  
  39. class B {
  40. public:
  41. B()
  42. : _b(0)
  43. {
  44. std::cout << __PRETTY_FUNCTION__ << std::endl;
  45. }
  46. explicit B(int b)
  47. : _b(b)
  48. {
  49. std::cout << __PRETTY_FUNCTION__ << std::endl;
  50. }
  51. B(const B& rhs)
  52. : _b(rhs._b)
  53. {
  54. std::cout << __PRETTY_FUNCTION__ << std::endl;
  55. }
  56. B(B&& rhs)
  57. : _b(std::move(rhs._b))
  58. {
  59. std::cout << __PRETTY_FUNCTION__ << std::endl;
  60. }
  61. ~B() { std::cout << __PRETTY_FUNCTION__ << std::endl; }
  62.  
  63. void print() { std::cout << _b.get() << std::endl; }
  64.  
  65. private:
  66. A _b;
  67. };
  68.  
  69. B print(B&& b)
  70. {
  71. std::cout << typeid(b).name() << std::endl;
  72. b.print();
  73. B b2(2);
  74. return b2;
  75. }
  76.  
  77. int main()
  78. {
  79. {
  80. B b(B(1));
  81. // 1
  82. b.print();
  83.  
  84. B b2(std::move(B(10)));
  85. // 10
  86. b2.print();
  87.  
  88. // 1
  89. auto b3 = print(std::move(b));
  90. // 2
  91. b3.print();
  92. // std::move is just type casting function, don't move anything inside.
  93. // so we can call b.print() since print function doesn't move b.
  94. // 1
  95. b.print();
  96.  
  97. // 100
  98. auto b4 = print(std::move(B(100)));
  99. // 2
  100. b4.print();
  101.  
  102. // print function should get && (rvalue) reference only.
  103. //auto b5 = print(b);
  104. //b5.print();
  105.  
  106. }
  107.  
  108. std::cout << "A::~A() is called in " << test << " times." << std::endl;
  109. return 0;
  110. }
Add Comment
Please, Sign In to add comment