• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
7 // Tests swapping an array of arrays of swap_test_class objects by means of boost::swap.
8 
9 #include <boost/utility/swap.hpp>
10 #include <boost/core/lightweight_test.hpp>
11 #define BOOST_CHECK BOOST_TEST
12 #define BOOST_CHECK_EQUAL BOOST_TEST_EQ
13 
14 //Put test class in the global namespace
15 #include "./swap_test_class.hpp"
16 
17 #include <algorithm> //for std::copy and std::equal
18 #include <cstddef> //for std::size_t
19 
20 //Provide swap function in both the namespace of swap_test_class
21 //(which is the global namespace), and the std namespace.
22 //It's common to provide a swap function for a class in both
23 //namespaces. Scott Meyers recommends doing so: Effective C++,
24 //Third Edition, item 25, "Consider support for a non-throwing swap".
swap(swap_test_class & left,swap_test_class & right)25 void swap(swap_test_class& left, swap_test_class& right)
26 {
27   left.swap(right);
28 }
29 
30 namespace std
31 {
32   template <>
swap(swap_test_class & left,swap_test_class & right)33   void swap(swap_test_class& left, swap_test_class& right)
34   {
35     left.swap(right);
36   }
37 }
38 
39 
main()40 int main()
41 {
42   const std::size_t first_dimension = 3;
43   const std::size_t second_dimension = 4;
44   const std::size_t number_of_elements = first_dimension * second_dimension;
45 
46   swap_test_class array1[first_dimension][second_dimension];
47   swap_test_class array2[first_dimension][second_dimension];
48 
49   swap_test_class* const ptr1 = array1[0];
50   swap_test_class* const ptr2 = array2[0];
51 
52   for (std::size_t i = 0; i < number_of_elements; ++i)
53   {
54     ptr1[i].set_data( static_cast<int>(i) );
55     ptr2[i].set_data( static_cast<int>(i + number_of_elements) );
56   }
57 
58   boost::swap(array1, array2);
59 
60   for (std::size_t i = 0; i < number_of_elements; ++i)
61   {
62     BOOST_CHECK_EQUAL(ptr1[i].get_data(), static_cast<int>(i + number_of_elements) );
63     BOOST_CHECK_EQUAL(ptr2[i].get_data(), static_cast<int>(i) );
64   }
65 
66   BOOST_CHECK_EQUAL(swap_test_class::swap_count(), number_of_elements);
67   BOOST_CHECK_EQUAL(swap_test_class::copy_count(), 0);
68 
69   return boost::report_errors();
70 }
71