immutable
Ellery Newcomer
ellery-newcomer at utulsa.edu
Wed Jan 26 12:54:16 PST 2011
On 01/26/2011 02:40 PM, Steven Schveighoffer wrote:
> On Wed, 26 Jan 2011 15:32:58 -0500, Robert <robert.welin at hotmail.com>
> wrote:
>
>>
>> Hello,
>> I have just recently started programming in D (a very pleasant
>> experience so
>> far I must say), but when experimenting with the the immutable
>> attribute I
>> discovered that the following code does not generate a compile time nor a
>> runtime error:
>>
>> //Decalare immutable string
>> immutable char[] buf = "hello";
>>
>> //Print the value of buf
>> writefln("buf = %s",buf);
>>
>> //Change buf by using standard input
>> stdin.readln(buf);
>>
>> //Print buf again
>> writefln("buf = %s",buf);
>>
>>
>> This is a bit confusing to be because I had assumed that immutable
>> data really
>> would be immutable (without casting). Why does the code above work?
>>
>
> It shouldn't. I don't know where the bug is. Please file a bug with a
> complete program (with a main() function) here:
> http://d.puremagic.com/issues/enter_bug.cgi
>
> BTW, this has a segfault in Linux, so it's definitely trying to
> overwrite immutable data.
>
> -Steve
I'd guess this is the problem:
void badurk(C,E)(ref C[] x, E y){
x ~= y;
}
void main(string[] args){
immutable char[] buf = "hello";
static assert(is(typeof(buf) == immutable(char[])));
badurk(buf,'a'); //compiler: la la, this is okay!
}
OT: this function confuses me:
size_t readln(C)(ref C[] buf, dchar terminator = '\n') if (isSomeChar!C)
{
static if (is(C == char))
{
enforce(p && p.handle, "Attempt to read from an unopened
file.");
return readlnImpl(p.handle, buf, terminator);
}
else
{
// TODO: optimize this
string s = readln(terminator);
if (!s.length) return 0;
buf.length = 0;
foreach (wchar c; s) //// <----- (?!)
{
buf ~= c;
}
return buf.length;
}
}
More information about the Digitalmars-d
mailing list