auto storage class - infer or RAII?

Boris Kolar boris.kolar at globera.com
Tue Nov 14 01:15:01 PST 2006


== Quote from Sean Kelly (sean at f4.ca)'s article
>      MyClass c = scope MyClass();
>      MyClass c = new(scope) MyClass();
> Both would allow data to be allocated on the stack without escape
> detection (or an assumption that the user isn't being evil), and the
> latter is even almost identical to how alloca is used now.

I like the above suggestions. After thinking about it, I'm beginning to wonder if
scoped variables are usefull at all. The way I see it, there are three cases,
where one might desire scoped variables:

1. Guaranteed, deterministic finalization (mostly disposal of system resources).
For example, file should be closed when going out of scope. In this case, it would
be better to make File class scoped, not individual variables:
    auto/scoped/whatever class File {
        this() { ... }
        ~this() { close; }
    }

2. Avoiding garbage collection. This can be accomplished, for example, with custom
allocation (stack, for example). We can solve this by allowing a single parameter
of type DeterministicAllocator to 'new' keyword in all cases (even if 'new' is not
overriden in class). Maybe Allocator should be defined as a 'void* delegate()'.
For example:
    // defined in Phobos and treated as special by compiler
    typedef void* delegate() DeterministicAllocator;

    class Foo {
        // 'new' is NOT defined here
    }
    void test() {
        DeterministicAllocator myOwnAllocator = stackAllocator;
        Foo foo = new(myOwnAllocator) Foo();
    }

3. Some aspects of 'value class' semantics are required. Note that 'scope' or
'auto' didn't solve this problem. The best way to solve this is to make structs
more powerful (allow inheritance, possibly even interface implementation, default
constructors, destructors, but do NOT allow virtual/overriden methods). For example:
    struct BigInteger: BigCardinal {
        ~this() {
            dispose;
        }
        bool negative;
    }

In either case, we don't really need scoped variables at all.



More information about the Digitalmars-d mailing list