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.

Reply via email to