www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Don't allow to reassign, but content is editable

reply tcak <tcak gmail.com> writes:
In javascript, with "const" keyword, you assign an object to a 
variable. Later, you cannot assign anything else to that 
variable, but content of it still can be changed. No matter by 
using "immutable" or "const", I cannot imitate that. Is there a 
way to do this without an overhead (like calling a function to 
create a pointer)?

Example:

class Test
{
     public int[] a;

     public this(){ a = new int[5]; }

      property auto b(){ return a.ptr; }  // this is a 
possibility, but results with overhead of calling. Also, b is not 
an array anymore, just int*.
}

I want this to be possible:
test.a[3] = 7;

But this wouldn't be allowed:
test.a = new int[14];
Apr 07 2021
next sibling parent Adam D. Ruppe <destructionator gmail.com> writes:
On Wednesday, 7 April 2021 at 12:28:25 UTC, tcak wrote:
      property auto b(){ return a.ptr; }  // this is a 
 possibility, but results with overhead of calling. Also, b is 
 not an array anymore, just int*.
Why are you returning a.ptr instead of just a? If you return just a, it works fine for what you want. You can virtually guarantee no calling overhead by simply making that `final`; then it is easy for the compiler to inline in all cases.
Apr 07 2021
prev sibling parent Kagamin <spam here.lot> writes:
struct A
{
     private int[] a;
     this(int[] b){a=b;}
     int[] c(){ return a; }
      disable void opAssign();
}
struct B
{
     A a;
     this(int){ a=new int[5]; }
     int[] b(){ return a.c; }
     void f(){ a=new int[5]; }
}
Apr 07 2021