How do I make only the array itself immutable?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Mar 15 02:21:23 UTC 2018


On Thursday, March 15, 2018 02:06:23 Marc via Digitalmars-d-learn wrote:
> Can I make it work?
>
> >struct S
> >{
> >
> > int[] l;
> >
> >}
>
> then
>
> >auto s = S();
> >s.l ~= 1; // ok
> >s.l = []; // error

It's not possible to do anything like that, and it really doesn't make sense
when you consider how dynamic arrays work. A dynamic array is essentially

struct DynamicArray(T)
{
    size_t length;
    T* ptr;
}

If you do const(T[]), then that would be like having

struct DynamicArray
{
    const size_t length;
    const(T*) ptr;
}

whereas if you have const(T)[], then that would be like

struct DynamicArray
{
    size_t length;
    const(T)* ptr;
}

Either way, in order to append to a dynamic array, the length must be
mutated, and the ptr will potentially be mutated (that depends on whether
the slice of memory that the dynamic array refers to has room to be appended
to in place or whether a new buffer has to be allocated). So, to append to a
dynamic array, the only thing that can be const or immutable is the data
pointed to by the pointer. And to prevent assigning a new value to a dynamic
array, the whole thing would have to be const or immutable. So, if you
prevent assigning to a dynamic array, you also prevent appending to it. And
for that matter, if you prevent appending to it, you prevent assigning to
it. On some level, appending _is_ assigning.

If you want to have a dynamic array which you can append to but can't
explicitly assign a new value to, you'll have to wrap it in a struct with
the appropriate operators overloaded and use that instead of using a dynamic
array directly. But if the reason you want to prevent the assignment has
anything to do with wanting to prevent the ptr from changing, then you'll
pretty much have to give up on appending, because if the dynamic array's
capacity isn't large enough to append to in place, it's going to allocate a
new buffer and change the ptr value.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list