Why is 'scope' so weak?

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Tue Nov 23 05:16:26 PST 2010


On Tue, 23 Nov 2010 12:59:27 +0000, Lars T. Kyllingstad wrote:

> [...]


Here's a fun example, which compiles and runs without error.  It may seem 
contrived, but it shows that all it takes is someone forgetting to remove 
'scope' when they change the implementation of a function, and memory 
corruption ensues.

    void delegate() globalDg;
    void call(scope void delegate() dg)
    {
        dg();

        // Don't tell anyone, but I'm saving this for later ;)
        globalDg = dg;
    }


    void foo()
    {
        int i;
        void izero() { i = 0; }
        call(&izero);
        assert (i == 0); // As expected
    }


    void bar()
    {
        int x = 123;

        // Simply calling some function cannot possibly
        // do anything to x...
        globalDg();

        // ...or can it?
        assert (x == 0);
    }


    void main()
    {
        foo();
        bar();
    }


More information about the Digitalmars-d mailing list