Asking a const-related fix [Was: Re: DMD workforce contribution]

Timon Gehr timon.gehr at gmx.ch
Mon Nov 7 09:39:58 PST 2011


On 11/07/2011 05:13 PM, Gor Gyolchanyan wrote:
> I think the problem arises because in order for this to be fully safe,
> the constructor needs to be called before the object is allocated (by
> making an always-writable temporary) because otherwise the members
> could end up in ROM and physically immutable to the constructor.
>
> On Mon, Nov 7, 2011 at 8:08 PM, Timon Gehr<timon.gehr at gmx.ch>  wrote:
>> On 11/07/2011 11:57 AM, Jonathan M Davis wrote:
>>>
>>> That would be altering aa, which isn't legal. const variables can be
>>> initialized but _can't_ be assigned to. If you want to do something
>>> fancier
>>> than a simple initialization, you're going to need to create another array
>>> which you do everything to and _then_ initialize the const array with
>>> that.
>>> The errors that you're running into are completely by design.
>>>
>>
>> What bearophile is asking for is to treat those cases like an initialization
>> (what they, in fact, are) rather than like an assignment.
>>

No. Things don't 'end up in ROM' the compiler puts them there. Afaik, 
currently, only static immutable data ends up there. And even then that 
is not real ROM, it is just an OS-enforced convention. That is really 
not the issue here. What makes the implementation non-trivial is the 
fact that the compiler would have to enforce in some conservative way 
that upon exit of the constructor only one reference to the dynamic 
array exists.

Initalization of immutable members is somewhat moot anyways, consider this:

import std.stdio;

immutable(int)* p;

void foo(){ // checks if values pointed to by p are really immutable
	static int[immutable(int)*] mem;

	if(p !in mem) mem[p] = *p;
	else assert(mem[p] == *p); // fail.
}

struct Foo{
	immutable int x;
	
	this(int y){
		p=&x;
		foo();
		x=1;
		foo();
	}
}

void main(){
	auto foo=Foo(2);
}

I think the current initialization semantics are not restrictive enough.


More information about the Digitalmars-d mailing list