2012-07-29 73 views
1

D在隱式函數實例化過程中丟棄頂層數組的常量,並在明確函數實例化時將其保留。 考慮代碼: 在隱式函數實例化期間數組常量丟棄

// main.d 
import std.stdio; 
void foo(T)(T val) 
{ 
    writeln(typeid(T)); 
} 
void main() 
{
const int[] arr; writeln(typeid(arr)); // actual type foo(arr); // implicit instantiation foo!(typeof(arr))(arr); // explicit instantiation }
...和D中的輸出:
$ dmd main.d && ./main 
const(const(int)[]) 
const(int)[] 
const(const(int)[]) 
As you can see, top level const was lost in case of implicit instantiation. Is this bug, feature or my misunderstanding ?

回答

2

What's lost is the constness of the array pointer - not the constness of the array itself.

const int[]保護數組指針(不能指向不同的數組)和數組數據(不能更改元素)。這就是爲什麼第一個和第三個輸出中有兩個const。但是,將數組傳遞給函數時,不需要保持指針的常量 - 如果將foo中的val更改爲不同的數組,它將不會影響main函數中的arr的內容。