by EpicEng · 11y ago · 0 comments
I prefer working in python to C++, I just wish I had a lot more control over things like this. And no, __del__ isn't a good solution as that opens a whole can of worms (for one, it's not guaranteed to ever be called).
a(b(c()))
because just returning an object, then dropping the reference at the end of 'a' would do just that. You could also write your own context manager to wrap up a parameter. class Shadow(object):
def __init__(self):
self.value = None
def __enter__(self):
return self
def set(self, v):
self.value = v
def __exit__(self, *args):
if self.value is not None:
self.value.cleanup()
with Newdb() as db, Shadow() as d:
a(b(c(db, d))) with a(b(c)) as f:
but then you risk any of those functions throwing an exception and screwing up the whole thing. You can move the resource allocation from __init__ to __enter__, but now you split your initialization code over 2 constructors. You can just hope and pray that a and b don't throw an exception, but someone is gonna accidentally break that assumption. And even if they don't, you've now spent more time worrying about that then if you just did manual memory allocation.Or, in C++ you write
class Foo {
public:
Foo() {/*get handle*/}
~Foo() {/*release resource*/}
};
and you never have to worry again. with alloc_resource() as resource:
resource.use() {
Type obj;
// do stuff
}
// obj destructor just ran
C# and other languages have similar paradigms, but they require more attention to detail than a destructor does.What its really saying is if the lifetime is automatic or manual.
Maybe I'm confusing C with C++ or just outright confused, but to my understanding, nothing says that:
int foo[] = <massive amount of data>;
actually has to live on the stack.This might be possible in theory but I've never seen it in practice.