On Thursday, 19 December 2013 at 07:31:28 UTC, ilya-stromberg wrote:
What should we do if we decide that we need REAL `const` postblit/constructor? I mean postblit/constructor that creates only `const` object that can't be implicitly converted to the `mutable` or `immutable`.

D is not C/C++. Objects are either mutable or immutable. Sometimes you can view any of them through const. There are no const objects per se.

BTW, it looks like it's quite easy to implement `unique` storage class only for local scope (only for function body). For example:

immutable(int)[] foo()
{
   //it's unique variable because I created it
   unique arr = new unique int[2];

//I can change unique variable because only I have reference for it
   arr[0] = 10;
   arr[1] = 20;

//unique variable can be implicitly converted to the immutable variable
   return arr;
}

So, `unique` storage class allows to avoid unsafe `cast(immutable)` cast. It's often use case, see also `std.exception.assumeUnique`. So, I think it will be great to have reserved `unique` keyword for `unique` storage class.

Current implementation can be characterized by complete absence of sane escape analysis.

import std.stdio;
import core.memory;

class A
{
   int *ptr;
   ~this()
   {
      (*ptr)++;
   }
}

pure foo()
{
   A a = new A;
   int* ptr = new int;
   a.ptr = ptr;
   a = null;
   return ptr;
}

void main()
{
   immutable int* ptr = foo();
   writeln(*ptr); // it is 0
   GC.collect();
   writeln(*ptr); // it is 1 now
}

Your proposal suffers from same issue. Although idea of unique can be worthy, without escape analysis it is another hole.

Reply via email to