3 ms·
The issue you mention of not knowing the lifetime is something that happens with pointers and memory allocations as well in C++. Unless it is documented it can
by calloc 15y ago
The issue you mention of not knowing the lifetime is something that happens with pointers and memory allocations as well in C++. Unless it is documented it can be a pain trying to figure out who is ultimately responsible for free'ing the memory that was allocated ...
Ultimately Garbage Collection would help there, but I am not sure we are going to see that in C++ anytime soon.
- barrkel 15y agoYes, but the solution landscape to this problem domain is different. Automatic variables have well-defined lifetimes; they die when they go out of scope. This means there's greater scope for the compiler to take more initiative about lifetime of captured variables (which will all be automatic one way or another, i.e. implicit 'this', a local or a parameter; assume reference parameters etc. cannot be captured). When I designed and implemented the same feature, anonymous methods in Delphi, I used reference counting to keep alive a heap-allocated activation record containing all captured variables. This works well for most scenarios; it can get into knots in more obscure situations where you have recursive lambdas that call themselves via a captured variable, but those are usually pretty rare. You're right that GC is a help. The biggest thing GC gives you is freedom from having to worry about who controls the lifetime of parameters and function return values, in most cases. In the presence of GC, you can get more clever about your algorithms and data structures; you can cache and memoize, without paranoid concern for things disappearing behind your back. Consider a querying API that takes in closures for sorting and selection functions; I can see it building up temporary results and caching them, or streaming results in a multi-threaded fashion, but it can only do that if it can reliably hang on to closures after the select/sort/etc. function has returned.
- stephen_g 15y agoWhat would garbage collection do that C++0x's shared_ptr smart pointer (which is reference counted) doesn't? I'm not really sure how GC works but using normal memory allocation when you can and reference counted pointers when somebody else is responsible for deallocating objects seems to be adequate and is still high performance...
- zwieback 15y agoThat's what I was thinking when reading the article. It almost seems like capturing stack variables by reference should not be allowed at all but that would be too restrictive. Ultimately the C++ problems have to be resolved by conventions and idioms, just like we've all learned to be careful when passing a pointer to a local variable.