What is shared functions?

simendsjo simendsjo at gmail.com
Mon Oct 24 09:01:07 PDT 2011


On 24.10.2011 17:23, Steven Schveighoffer wrote:
> On Sun, 23 Oct 2011 08:32:34 -0400, simendsjo <simendsjo at gmail.com> wrote:
>
>> What does shared for functions mean? I thought it was supposed to
>> automatically synchronize access, but this doesn't seem to be the case.
>>
>> void f() shared {
>> // no synchronization
>> }
>>
>> void f() {
>> synchronized {
>> // do stuff
>> }
>> }
>
> Shared functions do not affect the function. All they do is affect the
> 'this' pointer.
>
> This:
>
> struct S
> {
> void f() shared {}
> }
>
> is roughly equivalent to this:
>
> struct S
> {}
>
> void f(shared ref Foo this){}
>
> -Steve


So you cannot create a function to be called on both shared and unshared 
instances? For mutable/immutable there's const, but there is no 
"maybeShared".

struct S {
     void onlyShared() shared {}
     void notShared() {}
}

void main() {
     shared s1 = cast(shared)new S();
     s1.onlyShared(); // ok
     //s1.notShared(); // error: not callable using argument types () shared
     auto s2 = new S();
     //s2.onlyShared(); // error: not callable using argument types ()
     s2.notShared(); // ok
}


More information about the Digitalmars-d-learn mailing list