| 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 | |
| 6 | // run-time test for "boost/core/ref.hpp" header content |
| 7 | // see 'ref_ct_test.cpp' for compile-time part |
| 8 | |
| 9 | #include <boost/core/ref.hpp> |
| 10 | #include <boost/core/lightweight_test.hpp> |
| 11 | |
| 12 | namespace { |
| 13 | using namespace boost; |
| 14 | |
| 15 | template <class T> |
| 16 | struct ref_wrapper |
| 17 | { |
| 18 | // Used to verify implicit conversion |
| 19 | static T* get_pointer(T& x) |
| 20 | { |
| 21 | return &x; |
| 22 | } |
| 23 | |
| 24 | static T const* get_const_pointer(T const& x) |
| 25 | { |
| 26 | return &x; |
| 27 | } |
| 28 | |
| 29 | template <class Arg> |
| 30 | static T* passthru(Arg x) |
| 31 | { |
| 32 | return get_pointer(x); |
| 33 | } |
| 34 | |
| 35 | template <class Arg> |
| 36 | static T const* cref_passthru(Arg x) |
| 37 | { |
| 38 | return get_const_pointer(x); |
| 39 | } |
| 40 | |
| 41 | static void test(T x) |
| 42 | { |
| 43 | BOOST_TEST(passthru(ref(x)) == &x); |
| 44 | BOOST_TEST(&ref(x).get() == &x); |
| 45 | |
| 46 | BOOST_TEST(cref_passthru(cref(x)) == &x); |
| 47 | BOOST_TEST(&cref(x).get() == &x); |
| 48 | } |
| 49 | }; |
| 50 | |
| 51 | struct copy_counter { |
| 52 | static int count_; |
| 53 | copy_counter(copy_counter const& /*other*/) { |
| 54 | ++count_; |
| 55 | } |
| 56 | copy_counter() {} |
| 57 | static void reset() { count_ = 0; } |
| 58 | static int count() { return copy_counter::count_; } |
| 59 | }; |
| 60 | |
| 61 | int copy_counter::count_ = 0; |
| 62 | |
| 63 | } // namespace unnamed |
| 64 | |
| 65 | template <class T> |
| 66 | void do_unwrap(T t) { |
| 67 | |
| 68 | /* typename unwrap_reference<T>::type& lt = */ |
| 69 | unwrap_ref(t); |
| 70 | |
| 71 | } |
| 72 | |
| 73 | void unwrap_test() { |
| 74 | |
| 75 | int i = 3; |
| 76 | const int ci = 2; |
| 77 | |
| 78 | do_unwrap(t: i); |
| 79 | do_unwrap(t: ci); |
| 80 | do_unwrap(t: ref(t&: i)); |
| 81 | do_unwrap(t: cref(t: ci)); |
| 82 | do_unwrap(t: ref(t: ci)); |
| 83 | |
| 84 | copy_counter cc; |
| 85 | BOOST_TEST(cc.count() == 0); |
| 86 | |
| 87 | do_unwrap(t: cc); |
| 88 | do_unwrap(t: ref(t&: cc)); |
| 89 | do_unwrap(t: cref(t: cc)); |
| 90 | |
| 91 | BOOST_TEST(cc.count() == 1); |
| 92 | BOOST_TEST(unwrap_ref(ref(cc)).count() == 1); |
| 93 | } |
| 94 | |
| 95 | int main() |
| 96 | { |
| 97 | ref_wrapper<int>::test(x: 1); |
| 98 | ref_wrapper<int const>::test(x: 1); |
| 99 | unwrap_test(); |
| 100 | return boost::report_errors(); |
| 101 | } |
| 102 |
