Re: Interesting C++ way to allocate user data (placement new)
[
Date Prev][
Date Next][
Thread Prev][
Thread Next]
[
Date Index]
[
Thread Index]
- Subject: Re: Interesting C++ way to allocate user data (placement new)
- From: Patrick Rapin <toupie300@...>
- Date: 2012年5月16日 09:14:07 +0200
> Just wanted to share this idea:
>
> void * operator new( size_t size , lua_State * L )
> {
> return lua_newuserdata( L , size );
> }
> Foo * foo = new ( L ) Foo( constructor arguments );
Nice idea. It is a cleaner replacement to the more common idiom:
Foo * obj = new(lua_newuserdata(L, sizeof(Foo )) Foo (constructor arguments );
One could then get a step further and specify the metatable registry
name typically associated with the userdata.
void * operator new( size_t size , lua_State * L, const char* metaname )
{
void* obj = lua_newuserdata( L , size );
luaL_getmetatable(L, metaname);
lua_setmetatable(L, -2);
return obj;
}
So:
Foo * foo = new ( L, "FooMetatable" ) Foo( constructor arguments );