const in functions

Hipreme msnmancini at hotmail.com
Sun Mar 12 15:59:21 UTC 2023


On Sunday, 12 March 2023 at 15:09:45 UTC, Salih Dincer wrote:
> Hi,
>
> As someone who has used const very little in my life, I want to 
> learn and ask: What are consts used in function parameters for; 
> isn't there a copy already?
>


Const is used for you not be able to change your values inside 
references. This is why we have const methods for example:

```d

     class Test
     {
         private int a;
         int getA() const {return a;}
     }
     ```

By having this property in your method, it says you're 
guaranteeing that Test won't be changed when this method is 
called, then, it'll be less time trying to find what mutated the 
object, so, use it as much as you can, but never overuse it since 
it is a pain to deal with.

Const for value types is also used for not mutating them inside 
the function also leading to less debugging.

Another use case for them is for compiler being able to infer 
some optimizations. If your variable is `immutable`, it becomes 
implicitly `__gshared`, which does not uses Thread Local Storage, 
another good thing for optimization in both memory and access.


More information about the Digitalmars-d-learn mailing list