"shared" woes: shared instances of anonymous classes

Arafel via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 7 04:47:19 PDT 2017


Well, in both snippets there and extra closing parenthesis... they are 
obviously a typo, blame copy and pasting and not cleaning up afterwards :)

On 07/07/2017 11:14 AM, Arafel wrote:
> Hi!
> 
> I'm trying to wrap my mind around "shared", and I think I have managed 
> to more or less grasp it. However I'm having a problem, and it seems 
> it's just a missing feature (or rather combination of features) in the 
> language (or I haven't found the right keyword combination).
> 
> Is there any way to create a shared instance of an anonymous class? 
> Let's say:
> 
> ```
> class C {
>      shared this() { }
> }
> 
> void main() {
>      shared C c = new /* shared */ C {
>          shared this() {
>              super();
>          }
>      });
> }
> ```
> 
> This doesn't compile because, of course, the instantiation of the 
> anonymous class is not shared.
> 
> However, the following code doesn't compile either, and I'm not even 
> sure what "shared" is supposed to mean in this context:
> 
> ```
> class C {
>      shared this() { }
> }
> 
> void main() {
>      shared C c = new shared(C) {
>          shared this() {
>              super();
>          }
>      });
> }
> ```
> 
> I tried playing a bit around [1] (the non-shared constructors are 
> needed), and ended up even more confused than before!!
> 
> Of course if I create a proper named class D, I can instantiate shared 
> instances of D, so it's not like there's no workaround... still, coming 
> from Java I like anonymous classes, and I think it'd be cool to be able 
> to use them in this context.
> 
> If somebody knows how this works / is supposed to work, I'd be thankful!
> 
> [1]: https://dpaste.dzfl.pl/ce2ba93111a0



More information about the Digitalmars-d-learn mailing list