对于交换函数,我们有两种选择:参考样式:
void swap (int &a, int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
和指针样式:
void swap (int *a, int *b)
{
int temp;
temp = *b;
*b = *a;
*a = temp;
}
ref风格绝对合法,但指针风格有一些问题,当我们尝试使用此函数变量通过值传递,而不是通过引用传递,即使它们是指针-事实上,我们试图在函数之外使用局部变量的内存,并且可能在某一天,在某些机器中我们有未定义的行为,代码也适用于示例:在此代码中:
main()
{
//
{
int i=12;
int *j=&i;
}
//in this area, there is not variables i and j, but phisically threre is
// unsafe-relationship between this address: &i and what point to (12) ,
//any more logic according to this assumtion may be work
//but not safe -in the scene of undefined behavior-
我不知道你从哪里得到的关于函数外部的句子。你不应该相信他们,因为那句话是错的。
它应该是"在函数返回调用未定义行为后访问局部变量或参数"。(这是我自己的话。)
要获得正式的措辞,请查看C++标准。要查找的关键字是生存期、存储持续时间和未定义行为。