const in functions

Salih Dincer salihdb at hotmail.com
Sun Mar 12 15:09:45 UTC 2023


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?

```d
/*
  * Here's we have a class (Foo is partially simple):
  */
class Foo(T) {
   T x; // <----------- Because gonna just an int field!

   this(T n) { x = n; }

   override
   string toString() {
     import std.conv : text;
     return x.text;
   }
}
alias Int = Foo!int; // more simple...

import std.stdio : writeln;
import std.traits: isMutable;

/*
  * Let's simply use and test it!
  */
void main()
{
   auto n = new Int(41);
   auto r = (new Int(1)).inConst(n);/*
   auto r = (new Int(1)).outConst(n);
   assert( r.x == 42 &&
     !isMutable!( typeof(r) )
   );//*/

   n.writeln; // "41": It still has a value of 41.
   r.writeln; // "43": Added an extra 1 as expected!
}


// A, we can get its to guarantee us that parameters
// won't change:

auto inConst(T)(T a, const T b) // const
{ // it's not needed --^     but     ^-- why can't this be used

   a.x += 1; /* suppose it happened accidentally!
   ^-- it's already a new copy, right?//*/

   return new T(a.x + b.x); // Foo!int(43)
}


// B is used to guarantee that the returned result
// doesn't change:

const(T) outConst(T)(T a, T b)
{
   return new T(a.x + b.x);
}
```

In summary, we can use it in several places (in/out data, body, 
etc.) in a function. Is const needed if the compiler is copying? 
So why can't at the beginning of the body also be used and we get 
this error:

> source_file.d(38): Error: function 
> `source.inConst!(Foo!int).inConst` without `this` cannot be 
> `const`
> source_file.d(26): Error: template instance 
> `source.inConst!(Foo!int)` error instantiating

I appreciate the answers given because they hold a very important 
place in my life, thank you.

SDB at 79


More information about the Digitalmars-d-learn mailing list