On Mon, 27 Oct 2014 02:07:09 +0200 ketmar via Digitalmars-d-learn <digitalmars-d-learn@puremagic.com> wrote:
> > Thank you for clearing this up. If I understand correctly, > > __gshared is more of a hack to get C-like global variables, > > whilst shared is typed shared variable and more preferred? > yes and no. 'shared' is the part of the type, while '__gshared' is > not. i.e. > > shared int a; > pragma(msg, typeof(a)); // this will print "shared(int)" > > __gshared int b; > pragma(msg, typeof(b)); // this will print "int" > > you can't freely mix shared and non-shared types, so you must cast > 'shared' away on occasion and cast it back when necessary. this is not > safe and error-prone. > > '__gshared', for the other side, doesn't influence the type, so you > can have global variable which can be passed to other functions > without casting. > > but yes, generally this is a hack, and you'd better avoid '__gshared' > in idiomatic D code unless you are really really know what you are > doing and what consequences it may have. ;-) here is some silly code to show you some difference between 'shared' and '__gshared': void foo (ref int i) {} int a; shared int b; __gshared int c; void main () { foo(a); // this compiles foo(b); // this will not compile (see below) foo(c); // this compiles too } `foo(b);` will not compile, compiler emits error: "Error: function y01.foo (ref int i) is not callable using argument types (shared(int))" if you'll change `foo` to `void foo (ref shared int i) {}`, you'll get the opposite: `foo(a)` and `foo(c)` will be refused by compiler.
signature.asc
Description: PGP signature