原文 測試用例:
shared int[int] aa;
void main () {
cast()aa[1] = 1;//違反區間
}
原來工作正常.
你正在
aa[1]
上抛棄
共享
.該表達式是
通路值
,而不是
指派
.與定義
opIndex
和
opIndexAssign
的結構(表達式調用
opIndex
,而不是
opIndexAssign
)是一緻的.
如果使用
cast()(aa[1])=1
,即使在舊版本上也會出現區間錯誤.為何曾經
奏效
?
我認為舊編譯器解析其為
也适合
新
編譯器
且無區間錯誤的
(cast()aa)[1]
.
本例,
aa
也是
immutable
.我知道
使它
工作的
唯一方法
現在非常醜陋(丢棄不變也許就該醜?):
shared immutable int[int] aa;
void main () {
// (cast()aa)[1] = 1; // 無不變仍工作,
(*cast(int[int]*)(&aa))[1] = 1;//這樣?
}
有
靜态共享構造器
:
shared static this()
{
aa[1] = 1; /*不必強制轉換*/
}
但這樣不行的:
void f() {
aa[1] = 1; // 錯誤
}
shared static this()
{
f();//f仍然是模闆,模闆插件,仍不管用
//在f嵌套函數中不能初化aa不變量
}
int[int] make_aa() pure
{
int[int] maa;
maa[1] = 1; /*或函數調用等等*/
return maa;
}
immutable int[int] aa;
shared static this()
{
aa = make_aa();
}