How to check if an array is a manifest constant?
Jonathan M Davis
jmdavisProg at gmx.com
Sun Apr 3 16:31:47 PDT 2011
On 2011-04-03 08:29, simendsjo wrote:
> The behavior for manifest constant arrays is different from regular arrays
> and const/immutable arrays. The problem is that typeof() returns T[]. How
> can I see if the array is a manifest constant?
>
>
> void g(int[] x) { }
>
> const c = [1,2,3];
> static assert(is(typeof(c) == const(int[])));
> // cannot convert const(int[]) to int[]
> static assert(!__traits(compiles, g(c)));
> auto carr = c;
> static assert(is(typeof(carr) == const(int[])));
> assert(carr.ptr == c.ptr); // referenced
>
> immutable i = [1,2,3];
> static assert(is(typeof(i) == immutable(int[])));
> // cannot convert immutable(int[]) to int[]
> static assert(!__traits(compiles, g(i)));
> auto iarr = i;
> static assert(is(typeof(iarr) == immutable(int[])));
> assert(iarr.ptr == i.ptr); // referenced
>
> enum e = [1,2,3];
> // e is reported as int[] even if it's an enum
> static assert(is(typeof(e) == int[]));
> //static assert(is(typeof(e) == enum)); // not an enum (as expected)
> // it can be passed to funtions taking dynamic arrays
> void f(int[] x) {
> assert(e.ptr != x.ptr); // then the content is copied
> }
> f(e);
> // the behavior is different from other assignments
> // as the content is copied
> auto earr = e;
> assert(earr.ptr != e.ptr); // content is copied
There should be _no_ difference between arrays which are manifest constants
and regular arrays which are immutable except that they're computed at compile
time. However, there is currently a bug in CTFE which makes it so that an
array is copied _every_ time that it is accessed in CTFE (which, among other
things, causes a massive memory leak). I don't remember what the bug report is
for it, but Don is currently overhauling CTFE so that this won't be the case
anymore. So, this _should_ be fixed by the next release.
But there should be no need to worry about whether something is a manifest
constant or not. If there is, you're either doing something funny/wrong, or
it's because of a bug like the one that Don is fixing.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list