shared attribute

Jonathan M Davis jmdavisProg at gmx.com
Sun May 13 04:49:56 PDT 2012


On Sunday, May 13, 2012 13:36:31 japplegame wrote:
> Thanks.
> Another question.
> 
> This doesn't compile:
> >shared char[] s = "shared text".dup;
> 
> with error:
> >cannot implicitly convert expression ("shared text") of type
> >char[] to shared(char[])
> 
> Why do I need to write this?
> 
> >shared char[] s = cast(shared)"shared text".dup;
> 
> What is the meaning of this casting?

"shared text".dup is char[].

Note there is no shared, so it's thread-local. If you cast it to shared

auto s = cast(shared char[])"shared text".dup;

or

shared char[] s = cast(shared)"shared text".dup;

that makes the compiler treat that value as shared. As you just created the 
value, that's fine, but it's something that you need to be very careful of if 
there are other references to the same data, since the compiler will treat 
anything not marked as shared as thread-local. So, if you have one reference 
which is non-shared and one which is shared pointing to the same data, then 
you'll likely to end up with bugs in the code with the non-shared reference 
(since the compiler will make optimizations based on the fact that it's not 
shared).

You're forced to do the cast here, because you're dealing with a string 
literal rather than a type with a constructor. If it had a constructor, you'd 
do something more like

shared s = new shared(MyType)(args);

and no cast would be necessary.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list