c++ - GCC 或 Clang 关于函数参数的名称在其自己的默认参数范围内是否正确?

标签 c++ c++11 gcc clang language-lawyer

我有一个小玩具程序:

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/

相关文章:

c++ - 数组大小错误 x64 进程

c++ - 为什么 std::shared_ptr<void> 起作用

c++ - 为什么必须使用 'typename' 和 '::type' 前缀/后缀调用所有 type_traits 类?

使用 libxml2 的 C 代码在 Win 7 上的 cygwin 上给出编译时错误

multithreading - 不同平台的奇怪多线程输出

c++ - 二维动态字符数组cpp

c++ - 生命游戏 - 打印板到相同位置

c++ - 无法使用 Boost.process

c++ - 通过位移查找奇数除数

c++ - 了解虚拟析构函数