lua-users home
lua-l archive

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


On Mon, Oct 16, 2006 at 12:51:05PM -0700, Sam Roberts wrote:
> ....
> 
> 	// free resources
> ....
> }

But this is stripping C++ of one of its biggest advantages: automatic
destruction.  If this has to free manually, then it reopens the old
human error path to memory leaks.  (That is to say, memory leaks in
the normal path, not just leaks in the error path, which is what I
have now.)  It's also very tedious.

> Other idiom, as Rici (?) suggested and used in the PIL, is to first
> create something that WILL be garbage-collected, like a user-data, then
> put your two std::string inside the user-data. If lua longjmps out of
> your code, lua will still have the UD on the stack, and lua will know it
> needs to be garbage collected, and in the __gc metamethod you can
> destroy the s1 and s2.

That means every object that I might want to create inside a binding
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 ...

It might be worth it for strings, though.  SArg() could construct the
std::string, convert the stack element to the userdata containing it,
and return a reference to it (the C++ kind; string &), so it'd be mostly
transparent.  That way, at least the "Lua::Push(L, p->Func(SArg(1), IArg(2))"
shorthand bindings would remain concise (grab arguments, pass to
the bound function, push the result according to its type).

> I guess if code is large enough, then refactor into parts of code that
> allocates resources, and into a function that uses those resources and
> may error(). pcall the function that may error.
> 
> Its hard to have the benefits of C++ automatic resource freeing with
> exceptions, without paying the costs for exceptions!

Not at all.  If I have error cases, I return them in the traditional way:
through error returns.  I avoid doing things that can cause fatal errors
inside ctors.  This is a very practical scheme; this codebase is something
like 300k LOC (and seen four commercial releases), and if crypto++ is
disabled, can be built entirely without exceptions without hurting error
handling.

(You really do need exceptions if you want to handle OOM gracefully--there's
no other way to handle OOM from "new"--but, as a deliberate design tradeoff,
we don't do that.)

-- 
Glenn Maynard