using Data = char[10];
void f(Data x)
{
x = nullptr; // this compiles
}
void g(Data &x)
{
x = nullptr; // this does not compile, msvc complain "expression must be a modifiable lvalue
}
我很困惑为什么赋值表达式在 f 中编译,但在 g 中不编译。我预计这两个赋值都会失败,因为数组类型不可修改。
任何对 c++ 标准的引用都将不胜感激。
最佳答案
这与函数参数类型调整([dcl.fct]/5)有关:
After determining the type of each parameter, any parameter of type “array of T” or of function type T is adjusted to be “pointer to T”.
由于类型别名等同于它命名的类型,在第一种情况下,类型被确定为 char[10]
并调整为 char*
。您可以修改指针。
在第二种情况下,您形成了一个 char(&)[10]
。它是对数组的引用,数组无法赋值,即使是通过引用也是如此。
关于C++数组作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47386833/