简体   繁体   中英

C++ array as function parameter

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
}

I am confused why the assignment expression in f compiles, but does not compile in g. I expect that both assignment will fail since array type is not modifiable.

Any reference to c++ standard will be appreciated.

This has everything to do with function parameter type adjustment ( [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”.

Since a type alias is equivalent to the type it names, in the first case the type is determined as char[10] and adjusted to char* . You can modify a pointer.

In the second case, you form a char(&)[10] . It's a reference to an array, and arrays cannot be assigned to, even via a reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM