函数的形参可以是指针,此时将复制实参指针。与其他非引用类型的形参一样,该类形参的任何改变也仅作用于局部副本。如果函数将新指针赋给形参,主调函数使用的实参指针的值没有改变。
事实上被复制的指针只影响对指针的赋值。如果函数形参是非 const 类型的指针,则函数可通过指针实现赋值,修改指针所指向对象的值:
void reset(int *ip)
{
*ip = 0; // changes the value of the object to which ip points
ip = 0; // changes only the local value of ip; the argument is unchanged
}
调用 reset 后,实参依然保持原来的值,但它所指向的对象的值将变为 0:
int i = 42;
int *p = &i;
cout << "i: " << *p << '/n'; // prints i: 42
reset(p); // changes *p but not p
cout << "i: " << *p << endl; // ok: prints i: 0
如果保护指针指向的值,则形参需定义为指向 const 对象的指针:
void use_ptr(const int *p)
{
// use_ptr may read but not write to *p
}
指针形参是指向 const 类型还是非 const 类型,将影响函数调用所使用的实参。我们既可以用 int* 也可以用 const int* 类型的实参调用 use_ptr 函数;但仅能将 int* 类型的实参传递给 reset 函数。这个差别来源于指针的初始化规则。可以将指向 const 对象的指针初始化为指向非 const 对象,但不可以让指向非 const 对象的指针向 const 对象。