Teach adopt() to hold the adopted pointer in custom pointer type.
[luabind.git] / test / test_automatic_smart_ptr.cpp
blob496c25d9d49b6295032ab2f7bc147d97c622dab8
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)
5 #include "test.hpp"
6 #include <luabind/luabind.hpp>
7 #include <boost/shared_ptr.hpp>
9 struct X
11 X(int value)
12 : value(value)
14 ++alive;
17 ~X()
19 --alive;
22 int value;
24 static int alive;
27 int X::alive = 0;
29 struct ptr
31 ptr(X* p)
32 : p(p)
35 ptr(ptr const& other)
36 : p(other.p)
38 const_cast<ptr&>(other).p = 0;
41 ~ptr()
43 delete p;
46 X* p;
49 X* get_pointer(ptr const& p)
51 return p.p;
54 std::auto_ptr<X> make1()
56 return std::auto_ptr<X>(new X(1));
59 boost::shared_ptr<X> make2()
61 return boost::shared_ptr<X>(new X(2));
64 ptr make3()
66 return ptr(new X(3));
69 void test_main(lua_State* L)
71 using namespace luabind;
73 module(L) [
74 class_<X>("X")
75 .def_readonly("value", &X::value),
77 def("make1", make1),
78 def("make2", make2),
79 def("make3", make3)
82 DOSTRING(L,
83 "x1 = make1()\n"
84 "x2 = make2()\n"
85 "x3 = make3()\n"
88 TEST_CHECK(X::alive == 3);
90 DOSTRING(L,
91 "assert(x1.value == 1)\n"
92 "assert(x2.value == 2)\n"
93 "assert(x3.value == 3)\n"
96 DOSTRING(L,
97 "x1 = nil\n"
98 "x2 = nil\n"
99 "x3 = nil\n"
100 "collectgarbage()\n"
103 assert(X::alive == 0);