Shall I use immutable or const while passing parameters to functions

Marco Leise via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Apr 9 15:47:51 PDT 2015


Am Tue, 07 Apr 2015 17:26:23 +0000
schrieb "tcak" <tcak at gmail.com>:

> On Tuesday, 7 April 2015 at 15:51:59 UTC, bearophile wrote:
> > tcak:
> >
> >> void dataProcessor( string giveMeAllYourData ){}
> >>
> >> dataProcessor( cast( immutable )( importantData[5 .. 14] ) );
> >>
> >>
> >>
> >> With Const,
> >>
> >> void dataProcessor( in char[] giveMeAllYourData ){}
> >>
> >> dataProcessor( cast( const )( importantData[5 .. 14] ) );
> >
> > Don't cast to const/immutable unless you have a good reason to 
> > do it, and you know what you are doing (and most times you 
> > don't know it).
> > More generally, minimize the number of cast() in your D 
> > programs. You can use a search to count how many "cast(" there 
> > are in your whole D codebase, and you can try to reduce that 
> > number.
> >
> > Bye,
> > bearophile
> 
> I am trying to avoid it as much as I can, though this "shared" 
> keyword is not leaving me alone. Most of the projects I am 
> working on use multiple threads, and I am mostly obliged to use 
> casting many times. I am getting worried some times about what 
> the compiler is doing when I do casting other than just changing 
> a simple understanding like taking the first byte of ulong when I 
> do casting, etc. Please do not suggesting to use __gshared. It is 
> ugly looking.

I'd advise you not to use shared, at least not for anything
more than core.atomic. It's not in a good state for general
use and not even mutexes or conditions in D are 'shared'. It
becomes really messy as soon as you have structs that contain
shared fields. I suggest you use __gshared. :)

-- 
Marco



More information about the Digitalmars-d-learn mailing list