// incorrect version of swap: The arguments are not changed!
void swap(int v1, int v2)
{
int tmp = v2;
v2 = v1; // assigns new value to local copy of the argument
v1 = tmp;
void swap(int &v1, int &v2)
{
int tmp = v2;
v2 = v1;
v1 = tmp;
}
// ok: swap acts on references to its arguments
void swap(int *v1, int *v2)
{
int tmp = *v2;
*v2 = *v1;
*v1 = tmp;
从 C 语言背景转到 C++ 的程序员习惯通过传递指针来实现对实参的访问。在 C++ 中,使用引用形参则更安全和更自然。
void swap(int v1, int v2)
{
int tmp = v2;
v2 = v1; // assigns new value to local copy of the argument
v1 = tmp;
} // local objects v1 and v2 no longer exist
//swap(i,j);
void swap(int &v1, int &v2)
{
int tmp = v2;
v2 = v1;
v1 = tmp;
}
//swap(i,j);
// ok: swap acts on references to its arguments
void swap(int *v1, int *v2)
{
int tmp = *v2;
*v2 = *v1;
*v1 = tmp;
}
//swap(&i,&j);
从 C 语言背景转到 C++ 的程序员习惯通过传递指针来实现对实参的访问。在 C++ 中,使用引用形参则更安全和更自然。