lua-users home
lua-l archive

Re: Lua error handling and C++

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Mon, Oct 16, 2006 at 05:05:45PM -0400, Glenn Maynard wrote:
> That means every object that I might want to create inside a binding
Not every object.
> needs to be handled in this way. Unfortunately, "delete p" where p is
> a void* will not call destructors--that would make it easy. I'm not
> a big fan of the "give everything in the world a base class" paradigm ...
Probably no way to avoid the tedium, but I'm not sure if you understood.
Create a single user-data that contains a pointer to a struct MyArgs {
std::string localA; std::string localB; }, and with a __gc pointing to a
function that calls delete on (struct MyArgs*) when the UD is
collected, the struct members will be destroyed.
Basically, this is a process of taking your stack variables, and putting
them on the heap, wrapped in a UD, so lua can tell you when to destroy
them, longjmp or no longjmp. Example is here:
 http://www.lua.org/pil/29.1.html
but instead of having a DIR object, have a struct MyArgs, and instead of
calling opendir() call new MyArgs, and instead of calling closedir(),
call delete.
This may be tedious, but it is easy to be confident its "correct". C++
takes care of calling the dtors for all struct members, you make sure
that you call delete once in the __gc metamethods correctly, and lua
makes sure that the __gc metamethod is called. Since there is nothing on
the stack that is a leakable resource, there is nothing on the stack
that can be leaked. Also, "local" variables get freed the same way
error() or not, when lua cleans up the the lua->C stack.
You asked for suggestions on "other ways", this is one other way.
Cheers,
Sam
> > Its hard to have the benefits of C++ automatic resource freeing with
> > exceptions, without paying the costs for exceptions!
> 
> Not at all.
What does that mean?
If you have way of getting automatic resource freeing across longjmp
without paying the cost for exceptions, why does this thread exist?

AltStyle によって変換されたページ (->オリジナル) /