array_of_array_of_class.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright (c) 2008 Joseph Gauterin, Niels Dekker
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. // Tests swapping an array of arrays of swap_test_class objects by means of boost::swap.
  7. #include <boost/utility/swap.hpp>
  8. #include <boost/core/lightweight_test.hpp>
  9. #define BOOST_CHECK BOOST_TEST
  10. #define BOOST_CHECK_EQUAL BOOST_TEST_EQ
  11. //Put test class in the global namespace
  12. #include "./swap_test_class.hpp"
  13. #include <algorithm> //for std::copy and std::equal
  14. #include <cstddef> //for std::size_t
  15. //Provide swap function in both the namespace of swap_test_class
  16. //(which is the global namespace), and the std namespace.
  17. //It's common to provide a swap function for a class in both
  18. //namespaces. Scott Meyers recommends doing so: Effective C++,
  19. //Third Edition, item 25, "Consider support for a non-throwing swap".
  20. void swap(swap_test_class& left, swap_test_class& right)
  21. {
  22. left.swap(right);
  23. }
  24. namespace std
  25. {
  26. template <>
  27. void swap(swap_test_class& left, swap_test_class& right)
  28. {
  29. left.swap(right);
  30. }
  31. }
  32. int main()
  33. {
  34. const std::size_t first_dimension = 3;
  35. const std::size_t second_dimension = 4;
  36. const std::size_t number_of_elements = first_dimension * second_dimension;
  37. swap_test_class array1[first_dimension][second_dimension];
  38. swap_test_class array2[first_dimension][second_dimension];
  39. swap_test_class* const ptr1 = array1[0];
  40. swap_test_class* const ptr2 = array2[0];
  41. for (std::size_t i = 0; i < number_of_elements; ++i)
  42. {
  43. ptr1[i].set_data( static_cast<int>(i) );
  44. ptr2[i].set_data( static_cast<int>(i + number_of_elements) );
  45. }
  46. boost::swap(array1, array2);
  47. for (std::size_t i = 0; i < number_of_elements; ++i)
  48. {
  49. BOOST_CHECK_EQUAL(ptr1[i].get_data(), static_cast<int>(i + number_of_elements) );
  50. BOOST_CHECK_EQUAL(ptr2[i].get_data(), static_cast<int>(i) );
  51. }
  52. BOOST_CHECK_EQUAL(swap_test_class::swap_count(), number_of_elements);
  53. BOOST_CHECK_EQUAL(swap_test_class::copy_count(), 0);
  54. return boost::report_errors();
  55. }