struct vs. class, int vs. char.

Denis Koroskin 2korden at gmail.com
Wed Apr 29 01:52:33 PDT 2009


On Wed, 29 Apr 2009 06:09:49 +0400, Daniel Keep <daniel.keep.lists at gmail.com> wrote:

>
>
> Denis Koroskin wrote:
>> ...
>
> Scope stack-allocating is an optimisation.  It doesn't guarantee it
> because that it's the point of scope.
>
> Given that you're hung-up about stack allocation, I can't imagine how
> you'd implement scope as a template.  Hell, I can't imagine how you'd
> implement Scope as a template for *any* of its behaviours.
>
> class Foo
> {
>     Scope!(Bar) _bar;
> }
>
> How do you guarantee deterministic destruction when it's inside a
> non-deterministic construct?
>
>   -- Daniel

Is that a challenge?

import std.stdio;

class Foo
{	
    this(int i, int j, int k) {
        writeln("Foo.this(): ", i, j, k);
    }
	
    ~this() {
        writeln("Foo.~this()");
    }
}

struct Scope(T)
{
    this(Args...)(Args args)
    {
        _data[] = T.classinfo.init[]; // shouldn't be needed
        __get.__ctor(args);
    }
	
    ~this()
    {
        __get.__dtor();
    }

    alias __get this;
	
    T __get()
    {
        return cast(T)_data.ptr;
    }

    static assert(is(T == class));
    
    private byte[__traits(classInstanceSize, T)] _data;
    //private byte[__traits(classInstanceSize, T)] _data = T.classinfo.init; // bug: doesn't work
}

void main()
{
    auto foo = Scope!(Foo)(1, 2, 3);
}

One more bug-o-feature is that Scope.ctor is not called when args set is empty:

auto foo = Scope!(Foo)(); // no Scope.__ctor is called and thus underlying Foo instance is left uninitialized. I never understood a rationale behind this "feature". I believe it's a hole.




More information about the Digitalmars-d mailing list