2012-07-29 32 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的内容。