Error: function `...` without `this` cannot be `const`

someone someone at somewhere.com
Wed Jun 30 19:40:40 UTC 2021


On Wednesday, 30 June 2021 at 18:10:52 UTC, Alexandru Ermicioi 
wrote:

> That is because const/immutable/shared are being applied on the 
>  object hence 'this' variable inside function body if function 
> is a member of a struct or class.

So this will make sense ONLY for an object's method right ?

> It doesn't make sense to have a const modifier on a simple 
> function. What will that const mean then in context of that 
> function? To what it will be applied?

I think of all the code I have I choose the worst example for 
asking advice on attribute placement !

Let's use @property instead of const:

```d
struct Foo
{
     @property int data() { return m_data; } // read property

     @property int data(int value) { return m_data = value; } // 
write property

   private:
     int m_data;
}
```

In the above example 
(https://dlang.org/spec/function.html#property-functions) 
@property is placed before the return type of the property and 
not after the parameters section.

At first I started to do the same, say, by intuition, but then I 
saw lots of examples like:

```d
string something() @property { return this.whatever; }
```

... and changed them accordingly.

Now I am not sure which is the correct way.

Thanks alexandri




More information about the Digitalmars-d-learn mailing list