test_singleton.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
  2. // test_singleton.cpp
  3. // (C) Copyright 2018 Robert Ramey - http://www.rrsd.com .
  4. // Use, modification and distribution is subject to the Boost Software
  5. // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt)
  7. // should pass compilation and execution
  8. #include <iostream>
  9. #include <boost/serialization/singleton.hpp>
  10. #include "test_tools.hpp"
  11. static int i = 0;
  12. struct A {
  13. int m_id;
  14. A() : m_id(++i) {}
  15. ~A(){
  16. // verify that objects are destroyed in sequence reverse of construction
  17. if(i-- != m_id) std::terminate();
  18. }
  19. };
  20. struct B {
  21. int m_id;
  22. B() : m_id(++i) {}
  23. ~B(){
  24. // verify that objects are destroyed in sequence reverse of construction
  25. if(i-- != m_id) std::terminate();
  26. }
  27. };
  28. struct C {
  29. int m_id;
  30. C() : m_id(++i) {}
  31. ~C(){
  32. // verify that objects are destroyed in sequence reverse of construction
  33. if(i-- != m_id) std::terminate();
  34. }
  35. };
  36. struct D {
  37. int m_id;
  38. D(){
  39. // verify that only one object is indeed created
  40. const C & c = boost::serialization::singleton<C>::get_const_instance();
  41. const C & c1 = boost::serialization::singleton<C>::get_const_instance();
  42. BOOST_CHECK_EQUAL(&c, &c1);
  43. // verify that objects are created in sequence of definition
  44. BOOST_CHECK_EQUAL(c.m_id, 1);
  45. const B & b = boost::serialization::singleton<B>::get_const_instance();
  46. BOOST_CHECK_EQUAL(b.m_id, 2);
  47. const A & a = boost::serialization::singleton<A>::get_const_instance();
  48. BOOST_CHECK_EQUAL(a.m_id, 3);
  49. std::cout << a.m_id << b.m_id << c.m_id << '\n';
  50. m_id = ++i;
  51. }
  52. ~D(){
  53. // verify that objects are destroyed in sequence reverse of construction
  54. if(i-- != m_id) std::terminate();
  55. }
  56. };
  57. int test_main(int, char *[]){
  58. return 0;
  59. }
  60. // note: not a singleton
  61. D d;