我有一个小玩具程序:
static int value = 0;
int function(int &value=value) {
return value;
}
int main() {
function();
}
使用 g++ 7.2 编译:
g++ -std=c++11 -Wall -Wextra test.cc -o test
没问题。
用clang++-3.9编译:
clang++-3.9 -std=c++11 -Wall -Wextra test.cc -o test
test.cc:3:25: error: default argument references parameter 'value'
int function(int &value=value) {
^~~~~
test.cc:8:5: error: no matching function for call to 'function'
function();
^~~~~~~~
test.cc:3:5: note: candidate function not viable: requires single argument 'value', but no arguments were provided
int function(int &value=value) {
^
2 errors generated.
卡布姆。谁是对的?
最佳答案
我认为 clang 是正确的。来自 basic.scope.pdecl :
The point of declaration for a name is immediately after its complete declarator (Clause [dcl.decl]) and before its initializer (if any), except as noted below. [ Example:
int x = 12;{ int x = x; }
Here the second x is initialized with its own (indeterminate) value. — end example ]
另外,来自 dcl.fct.default :
Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in a default argument, even if they are not evaluated. Parameters of a function declared before a default argument are in scope and can hide namespace and class member names
关于c++ - GCC 或 Clang 关于函数参数的名称在其自己的默认参数范围内是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48771614/