[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Interesting C++ way to allocate user data (placement new)
- From: Patrick Rapin <toupie300@...>
- Date: Wed, 16 May 2012 22:15:25 +0200
> I usually delay setting the metatable until the object is in a defined
> state, which is hard to do with this idiom. If the constructor of the object
> throws a C++ exception and you catch it the "__gc" routine the metatable
> refers to may call the destructor, which is a bad idea because the
> constructor failed.
You are right. But there is a simple workaround for this problem.
As Pablo Pissanetzky already mentioned, you also need a matching
delete operator to deal with exceptions.
That can me written as (untested) :
void operator delete( void* ptr, lua_State * L, const char* metaname )
This delete overload will only be called if an exception occurs inside
Providing that the constructor does not itself deal with the Lua
state, the userdata is still on the top of the stack when the function
is called, and it is easy to invalidate the metatable *before* the
__gc metamethod could be called.