I have a class that I use in my C++ code and in some Lua scripts. The relevant portion of the class looks like:
typedef boost::shared_ptr<Thing> ThingPtr; // convenient
class Thing
{
public:
Thing() { /* do some stuff */ }
~virtual Thing() { }
ThingPtr createThing()
{
ThingPtr thing(new Thing);
// initialization can't be done in constructor
thing->doSomeInit();
return thing;
}
// other stuff....
};
I expose this class in Lua (without using binding or anything "fancy"). Before I added the factory function, my Lua function to create a Thing looked like:
int MyLua::newThing(lua_State* L)
{
int size = sizeof(Thing);
// allocate a new Thing object in place
new ((Thing*)lua_newuserdata(L, size)) Thing();
luaL_setmetatable(L, "MyStuff.thing");
return 1;
}
Once I added the factory function I did something like:
int MyLua::newThing(lua_State* L)
{
int size = sizeof(Thing);
// allocate a new Thing object in place
Thing* thing = new ((Thing*)lua_newuserdata(L, size)) Thing();
thing->doSomeInit();
luaL_setmetatable(L, "MyStuff.thing");
return 1;
}
This is fine seemed fine except that now I want to make the constructor of Thing private in order to enforce the use of the factory function in other places in the C++ code. So, now I have something like:
int MyLua::newThing(lua_State* L)
{
int size = sizeof(Thing);
ThingPtr thing = Thing::createThing();
void* space = lua_newuserdata(L, size);
memcpy(space, client.get(), size);
luaL_setmetatable(L, "MyStuff.thing");
return 1;
}
My question is: is there a better way to do this? The call to memcpy makes me feel uncomfortable.