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 
5 #include "test.hpp"
6 #include <luabind/luabind.hpp>
7 #include <boost/shared_ptr.hpp>
8 
9 struct X
10 {
XX11     X(int value)
12       : value(value)
13     {
14         ++alive;
15     }
16 
~XX17     ~X()
18     {
19         --alive;
20     }
21 
22     int value;
23 
24     static int alive;
25 };
26 
27 int X::alive = 0;
28 
29 struct ptr
30 {
ptrptr31     ptr(X* p)
32       : p(p)
33     {}
34 
ptrptr35     ptr(ptr const& other)
36       : p(other.p)
37     {
38         const_cast<ptr&>(other).p = 0;
39     }
40 
~ptrptr41     ~ptr()
42     {
43         delete p;
44     }
45 
46     X* p;
47 };
48 
get_pointer(ptr const & p)49 X* get_pointer(ptr const& p)
50 {
51     return p.p;
52 }
53 
make1()54 std::auto_ptr<X> make1()
55 {
56     return std::auto_ptr<X>(new X(1));
57 }
58 
make2()59 boost::shared_ptr<X> make2()
60 {
61     return boost::shared_ptr<X>(new X(2));
62 }
63 
make3()64 ptr make3()
65 {
66     return ptr(new X(3));
67 }
68 
test_main(lua_State * L)69 void test_main(lua_State* L)
70 {
71     using namespace luabind;
72 
73     module(L) [
74         class_<X>("X")
75           .def_readonly("value", &X::value),
76 
77         def("make1", make1),
78         def("make2", make2),
79         def("make3", make3)
80     ];
81 
82     DOSTRING(L,
83         "x1 = make1()\n"
84         "x2 = make2()\n"
85         "x3 = make3()\n"
86     );
87 
88     TEST_CHECK(X::alive == 3);
89 
90     DOSTRING(L,
91         "assert(x1.value == 1)\n"
92         "assert(x2.value == 2)\n"
93         "assert(x3.value == 3)\n"
94     );
95 
96     DOSTRING(L,
97         "x1 = nil\n"
98         "x2 = nil\n"
99         "x3 = nil\n"
100         "collectgarbage()\n"
101     );
102 
103     assert(X::alive == 0);
104 }
105