exchange_move_test.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. Copyright 2018 Glen Joseph Fernandes
  3. (glenjofe@gmail.com)
  4. Distributed under the Boost Software License, Version 1.0.
  5. (http://www.boost.org/LICENSE_1_0.txt)
  6. */
  7. #include <boost/config.hpp>
  8. #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
  9. #include <boost/core/exchange.hpp>
  10. #include <boost/core/lightweight_test.hpp>
  11. class C1 {
  12. public:
  13. explicit C1(int i)
  14. : i_(i) { }
  15. C1(C1&& c)
  16. : i_(c.i_) { }
  17. C1& operator=(C1&& c) {
  18. i_ = c.i_;
  19. return *this;
  20. }
  21. int i() const {
  22. return i_;
  23. }
  24. private:
  25. C1(const C1&);
  26. C1& operator=(const C1&);
  27. int i_;
  28. };
  29. void test1()
  30. {
  31. C1 x(1);
  32. BOOST_TEST(boost::exchange(x, C1(2)).i() == 1);
  33. BOOST_TEST(x.i() == 2);
  34. }
  35. class C2 {
  36. public:
  37. explicit C2(int i)
  38. : i_(i) { }
  39. operator C1() const {
  40. return C1(i_);
  41. }
  42. int i() const {
  43. return i_;
  44. }
  45. private:
  46. C2(const C2&);
  47. C2& operator=(const C2&);
  48. int i_;
  49. };
  50. void test2()
  51. {
  52. C1 x(1);
  53. BOOST_TEST(boost::exchange(x, C2(2)).i() == 1);
  54. BOOST_TEST(x.i() == 2);
  55. }
  56. class C3 {
  57. public:
  58. explicit C3(int i)
  59. : i_(i) { }
  60. C3(C3&& c)
  61. : i_(c.i_) { }
  62. C3& operator=(C1&& c) {
  63. i_ = c.i();
  64. return *this;
  65. }
  66. int i() const {
  67. return i_;
  68. }
  69. private:
  70. C3(const C3&);
  71. C3& operator=(const C3&);
  72. int i_;
  73. };
  74. void test3()
  75. {
  76. C3 x(1);
  77. BOOST_TEST(boost::exchange(x, C1(2)).i() == 1);
  78. BOOST_TEST(x.i() == 2);
  79. }
  80. int main()
  81. {
  82. test1();
  83. test2();
  84. test3();
  85. return boost::report_errors();
  86. }
  87. #else
  88. int main()
  89. {
  90. return 0;
  91. }
  92. #endif