test_automatic_smart_ptr.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. // Copyright Daniel Wallin 2009. Use, modification and distribution is
  2. // subject to the Boost Software License, Version 1.0. (See accompanying
  3. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4. #include "test.hpp"
  5. #include <luabind/luabind.hpp>
  6. #include <boost/shared_ptr.hpp>
  7. struct X
  8. {
  9. X(int value)
  10. : value(value)
  11. {
  12. ++alive;
  13. }
  14. ~X()
  15. {
  16. --alive;
  17. }
  18. int value;
  19. static int alive;
  20. };
  21. int X::alive = 0;
  22. struct ptr
  23. {
  24. ptr(X* p)
  25. : p(p)
  26. {}
  27. ptr(ptr const& other)
  28. : p(other.p)
  29. {
  30. const_cast<ptr&>(other).p = 0;
  31. }
  32. ~ptr()
  33. {
  34. delete p;
  35. }
  36. X* p;
  37. };
  38. X* get_pointer(ptr const& p)
  39. {
  40. return p.p;
  41. }
  42. std::auto_ptr<X> make1()
  43. {
  44. return std::auto_ptr<X>(new X(1));
  45. }
  46. boost::shared_ptr<X> make2()
  47. {
  48. return boost::shared_ptr<X>(new X(2));
  49. }
  50. ptr make3()
  51. {
  52. return ptr(new X(3));
  53. }
  54. void test_main(lua_State* L)
  55. {
  56. using namespace luabind;
  57. module(L) [
  58. class_<X>("X")
  59. .def_readonly("value", &X::value),
  60. def("make1", make1),
  61. def("make2", make2),
  62. def("make3", make3)
  63. ];
  64. DOSTRING(L,
  65. "x1 = make1()\n"
  66. "x2 = make2()\n"
  67. "x3 = make3()\n"
  68. );
  69. TEST_CHECK(X::alive == 3);
  70. DOSTRING(L,
  71. "assert(x1.value == 1)\n"
  72. "assert(x2.value == 2)\n"
  73. "assert(x3.value == 3)\n"
  74. );
  75. DOSTRING(L,
  76. "x1 = nil\n"
  77. "x2 = nil\n"
  78. "x3 = nil\n"
  79. "collectgarbage()\n"
  80. );
  81. assert(X::alive == 0);
  82. }