important proposal: scope keyword for class members

Bill Baxter wbaxter at gmail.com
Sun Mar 8 15:55:28 PDT 2009


On Mon, Mar 9, 2009 at 7:12 AM, John Simon <zildjohn01 at gmail.com> wrote:
> Sean Kelly Wrote:
>
>> John Simon wrote:
>> > Sean Kelly Wrote:
>> >>
>> >> Oh, I should mention that I'm not sure how the compiler would handle
>> >> this scenario:
>> >>
>> >> class A { byte[16]; }
>> >> class B { byte[32]; }
>> >> class C {
>> >>      this( bool b ) {
>> >>          if( b ) o = new A;
>> >>          else    o = new B;
>> >>      }
>> >>      scope Object o;
>> >> }
>> >>
>> >> If I had to guess I'd say that the compiler would either reserve the max
>> >> size necessary to store both A or B, or that in non-trivial cases it
>> >> just wouldn't bother with reserving space for o at all.
>> >
>> > Wrong. The Object is constructed when it comes into scope, and destructed when it leaves scope. Classes can't have an 'opAssign', instead the reference is reassigned. Since the reference is invariant/immutable here, this throws a compile time error.
>>
>> I'm talking about a proposed new feature, not an existing one.  Please
>> take this example in context.
>
> Sorry man, I thought you were disputing with me. My apologies. Let me rephrase.
>
> I believe that 'scope' declared objects shouldn't allow an assignment of a derived type. Reasoning being that there wouldn't be enough stack space allocated for it.
>
> So in your example above, Object could only recieve a 'new Object', and nothing further down in the hierarchy.

I'm pretty sure that assigning to a scope class on the stack is not
done by copying the memory.  I'm pretty sure what happens is basically
something like follows.   This scope statement:

    scope foo = new TheClass;

Basically becomes this:

    static ubyte[sizeof_TheClass] _mem;
    auto foo = new(_mem.ptr)  TheClass;

Where new(addr) indicates a "placement new".  So the memory for the
initial instance is allocated on the stack, yes, but other than that
foo act just like any other class pointer.  In particular if you say
foo=otherfoo;  you're just reassigning the pointer, not actually doing
anything with the object allocated on the stack.  It just becomes
unreferenced junk.

And before Walter says it -- I know, I should use obj2asm and look at
the assembly to see for sure.

--bb



More information about the Digitalmars-d mailing list