exchange_test.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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/core/exchange.hpp>
  8. #include <boost/core/lightweight_test.hpp>
  9. void test1()
  10. {
  11. int i = 1;
  12. BOOST_TEST(boost::exchange(i, 2) == 1);
  13. BOOST_TEST(i == 2);
  14. }
  15. class C1 {
  16. public:
  17. explicit C1(int i)
  18. : i_(i) { }
  19. int i() const {
  20. return i_;
  21. }
  22. private:
  23. int i_;
  24. };
  25. void test2()
  26. {
  27. C1 x(1);
  28. BOOST_TEST(boost::exchange(x, C1(2)).i() == 1);
  29. BOOST_TEST(x.i() == 2);
  30. }
  31. class C2 {
  32. public:
  33. explicit C2(int i)
  34. : i_(i) { }
  35. operator C1() const {
  36. return C1(i_);
  37. }
  38. int i() const {
  39. return i_;
  40. }
  41. private:
  42. int i_;
  43. };
  44. void test3()
  45. {
  46. C1 x(1);
  47. BOOST_TEST(boost::exchange(x, C2(2)).i() == 1);
  48. BOOST_TEST(x.i() == 2);
  49. }
  50. class C3 {
  51. public:
  52. explicit C3(int i)
  53. : i_(i) { }
  54. C3(const C3& c)
  55. : i_(c.i_) { }
  56. C3& operator=(const C1& c) {
  57. i_ = c.i();
  58. return *this;
  59. }
  60. int i() const {
  61. return i_;
  62. }
  63. private:
  64. C3& operator=(const C3&);
  65. int i_;
  66. };
  67. void test4()
  68. {
  69. C3 x(1);
  70. BOOST_TEST(boost::exchange(x, C1(2)).i() == 1);
  71. BOOST_TEST(x.i() == 2);
  72. }
  73. int main()
  74. {
  75. test1();
  76. test2();
  77. test3();
  78. test4();
  79. return boost::report_errors();
  80. }