scope(~this)
thedeemon via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Mar 13 22:33:28 PDT 2017
On Monday, 13 March 2017 at 14:28:01 UTC, Inquie wrote:
> On Monday, 13 March 2017 at 05:18:18 UTC, Nicholas Wilson wrote:
>> On Sunday, 12 March 2017 at 21:38:44 UTC, Inquie wrote:
>>> Is there any easy way to create a scope for termination of
>>> the object?
>>>
>>> I have a template method that takes a type and allocates and
>>> deallocates based on that type.
>>>
>>> class bar
>>> {
>>> void foo(T)()
>>> {
>>> T x;
>>> alloc(x);
>>> scope(~this) dealloc(x); // hypothetical that wraps the
>>> statement in a lambda and deallocates in the destructor
>>>
>>> ... x must stay allocated until class instance
>>> termination(has to do with COM, can't release it in foo)
>>> }
>>>
>>> }
>>>
I think the feature you're asking for is too complicated/involved
for a language feature. Because it means there must be some
implicit array in each object of your 'bar' class that holds some
number of closures that will be executed in destructor. This
affects object's memory layout and raises questions of allocating
memory for those closures and since those closures will have
pointers to some data (like 'x' here) it affects garbage
collection. So there are a lot of things to be careful about and
things that might affect other language features we haven't
thought about yet. This is something quite big and something that
affects a lot of code, not just a couple of classes you'll write
in your one app. Probably it would be better to implement it as a
library feature. Just make a base class having a method for
registering such closures and calling them in destructor, and
inherit from it or just embed it in your 'bar'.
More information about the Digitalmars-d-learn
mailing list