ref_test.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright David Abrahams and Aleksey Gurtovoy
  2. // 2002-2004. Distributed under the Boost Software License, Version
  3. // 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. // run-time test for "boost/ref.hpp" header content
  6. // see 'ref_ct_test.cpp' for compile-time part
  7. #include <boost/ref.hpp>
  8. #include <boost/detail/lightweight_test.hpp>
  9. namespace {
  10. using namespace boost;
  11. template <class T>
  12. struct ref_wrapper
  13. {
  14. // Used to verify implicit conversion
  15. static T* get_pointer(T& x)
  16. {
  17. return &x;
  18. }
  19. static T const* get_const_pointer(T const& x)
  20. {
  21. return &x;
  22. }
  23. template <class Arg>
  24. static T* passthru(Arg x)
  25. {
  26. return get_pointer(x);
  27. }
  28. template <class Arg>
  29. static T const* cref_passthru(Arg x)
  30. {
  31. return get_const_pointer(x);
  32. }
  33. static void test(T x)
  34. {
  35. BOOST_TEST(passthru(ref(x)) == &x);
  36. BOOST_TEST(&ref(x).get() == &x);
  37. BOOST_TEST(cref_passthru(cref(x)) == &x);
  38. BOOST_TEST(&cref(x).get() == &x);
  39. }
  40. };
  41. struct copy_counter {
  42. static int count_;
  43. copy_counter(copy_counter const& /*other*/) {
  44. ++count_;
  45. }
  46. copy_counter() {}
  47. static void reset() { count_ = 0; }
  48. static int count() { return copy_counter::count_; }
  49. };
  50. int copy_counter::count_ = 0;
  51. } // namespace unnamed
  52. template <class T>
  53. void do_unwrap(T t) {
  54. /* typename unwrap_reference<T>::type& lt = */
  55. unwrap_ref(t);
  56. }
  57. void unwrap_test() {
  58. int i = 3;
  59. const int ci = 2;
  60. do_unwrap(i);
  61. do_unwrap(ci);
  62. do_unwrap(ref(i));
  63. do_unwrap(cref(ci));
  64. do_unwrap(ref(ci));
  65. copy_counter cc;
  66. BOOST_TEST(cc.count() == 0);
  67. do_unwrap(cc);
  68. do_unwrap(ref(cc));
  69. do_unwrap(cref(cc));
  70. BOOST_TEST(cc.count() == 1);
  71. BOOST_TEST(unwrap_ref(ref(cc)).count() == 1);
  72. }
  73. int main()
  74. {
  75. ref_wrapper<int>::test(1);
  76. ref_wrapper<int const>::test(1);
  77. unwrap_test();
  78. return boost::report_errors();
  79. }