函数参数和默认参数的求值顺序 [英] Evaluation order of function arguments and default arguments

查看:55
本文介绍了函数参数和默认参数的求值顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到以下情况:

#include <iostream>

int *p = 0;

int f() {
    p = new int(10);
    return 0;
}

void g(int x, int *y = p) {
    std::cout << y << std::endl;
}

int main() {
    g(f());
}

这很微妙,因为您通常不希望默认参数在对函数调用的求值过程中发生变化.我不得不看一下程序集以发现此错误.

This is quite subtle, since you usually don't expect the default arguments to change during their evaluation for the function call. I had to take a look at the assembly to spot this error.

现在我的问题是:因为没有任何关于函数参数的求值顺序的保证,这是否确实是未定义的行为?

Now my question is: Is this really undefined behavior, since there aren't any guarantees concerning the evaluation order of function arguments?

推荐答案

未指定函数参数的求值顺序(即确定值).编译器可以自由地以任何顺序执行它们,甚至在没有其他因素阻止编译器这样做的情况下,也可以将它们混合在一起.

The order of evaluation (i.e. determining the value) of function arguments is not specified. The compiler is free to execute them in any order, and even intermingled if there are no other factors stopping it from doing so.

默认参数的求值发生在调用方而不是被调用方的上下文中.因此,对于一个参数,必须调用f(),而对于另一个参数,则需要读取全局变量p.没有指定此顺序发生的顺序,因此可以在调用f()之前或之后读取全局变量.

Evaluation of default arguments happens in the context of the caller, not the callee. So the call to f() is necessary for one argument, and reading the global variable p for the other. Which order this happens in is not specified, so the global could be read before or after the call to f().

这篇关于函数参数和默认参数的求值顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆