0

I'm using Lua & luabind for the first time, and I've been wondering about the following issue. If I declare a singleton class in C++, and bind it to Lua, where I get its instance and call some methods, which language actually owns the instance?

The reason I'm wondering is because at the moment my program will occasionally segfault in the destructor of my singleton class. Is Lua trying to garbage collect it after the instance has already been destructed? If so, how do I prevent it from doing so? Here is the declaration:

public:
        static App* GetInstance();
        ~App();
        void Execute();

    private:
        App();

In Lua I call

app = App.getInstance()
app:execute()

and after everything has finished, it crashes. What exactly is happening here?

The luabind looks like this (lots of properties have been omitted)

module(L, "nge")
[
        class_<App>("App")
            .scope
            [
                def("getInstance", &App::GetInstance)
            ]
            .def("execute", &App::Execute)
]
Nelarius
  • 181
  • 2
  • 10

1 Answers1

0

You should take care of the lifetimes, since you are returning a naked pointer. Luabind might be deleting your instance. Perhaps you should switch to using a shared_ptr for your instance. Luabind can do that: http://www.rasterbar.com/products/luabind/docs.html#smart-pointers . The documentation of LuaBridge has a good chapter on that, which might help to understand the issue.

Dmitry Ledentsov
  • 3,620
  • 18
  • 28
  • Would that apply even to singleton classes? As such I am not creating the object _in_ Lua (I dont call `App()`), I just get the pointer returned by `getInstance()`. Nevertheless, this is a good idea, and I will try playing with smart pointers next! – Nelarius Jun 07 '13 at 10:53
  • yup, that should work. Luabind is "configured" to use boost::shared_ptr correctly wherever it is created - in luabind itself or outside. Just make sure, you do that consistently, initializing the instance to a shared_ptr as well – Dmitry Ledentsov Jun 07 '13 at 13:02
  • My `GetInstance()` now returns `boost::shared_ptr` and I bind the class to Lua with `class_ >("App")`, but it still crashes in the destructor. The really odd thing is that it doesn't _always_ crash in the destructor, occasionally the program will close normally. – Nelarius Jun 07 '13 at 21:35
  • do you keep the singleton instance in a boost::shared_ptr as well? – Dmitry Ledentsov Jun 08 '13 at 08:16
  • I initialize the singleton as `static boost::shared_ptr instance(new App()); return instance;`. – Nelarius Jun 08 '13 at 20:46
  • ok. Do you want to create a minimal debuggable example? It seems, the problem could be something else. – Dmitry Ledentsov Jun 09 '13 at 15:47