copy must be const?!?
Dom DiSc
dominikus at scherkl.de
Thu Jul 25 12:00:58 UTC 2024
On Thursday, 25 July 2024 at 08:42:29 UTC, Jonathan M Davis wrote:
> It's not a cast. Casts in D use the keyword, cast - e.g.
>
> return --(cast(T)x);
>
> Rather, Dennis' solution is constructing a value of the given
> type. For it to work, T must be constructible from an immutable
> T - which works with integer types but won't actually work with
> most types.
Ah! Good, so at least here I can use it. Fine.
Should also wor if the type has an appropriate constructor, e.g.
a copy constructor that takes a const parameter and returns a
mutable copy (as I would expect every copy constructor to do), so
at least in code I write, I will never have a problem.
> It also won't work with pointer types or reference types, since
> those would need new when constructing them.
Of course. For those that also wouldn't work for functions
instead of templates.
> And no, in general, you don't want to be casting away const or
> immutable. There are cases where it can work (e.g. if the cast
> does a copy, which it would with an integer type)
But a parameter given by value is ALWAYS a copy.
So if a copy is done, the copy should be mutable. I can't see why
that should ever be a problem. The compiler should never create
new values const or immutable unless explicitly advised to do so.
E.g.
```d
void fun(myType x) { }
```
called with immutable object should create a mutable x, because
```d
myType x = immutableObject;
```
will also create a mutable x. If I want an immutable x, i can do
```d
immutable myType = immutableObject;
```
```d
void fun(T)(T x) if (is(Unqual!T==myType)) { }
```
should also create a mutable x, for the same reason, because if I
want an immutable x, I can do
```d
void fun(T)(immutable(T) x) if (is(Unqual!T==myType)) { }
```
Therefore I consider the current behaviour a bug.
More information about the Digitalmars-d-learn
mailing list