函数的参数使用指针的引用,可以在函数中修改传入的指针的指向;
如下代码:
#include <iostream>
// 普通指针参数
void modifyPointerValue(int* ptr) {
int newValue = 10;
ptr = &newValue; // 修改指针本身,不会影响外部的原始指针
}
// 指针引用参数
void dangling_modifyPointerReference(int*& ptr) {
int newValue = 0; // 局部变量被销毁,产生了悬空指针
ptr = &newValue; // 修改指针本身,会影响外部的原始指针
}
// 指针引用参数
void modifyPointerReference(int*& ptr) {
int *newValue = new int(0);
ptr = newValue; // 修改指针本身,会影响外部的原始指针
}
int main() {
int value = 5;
int* ptr = &value;
std::cout << "Before modifyPointerValue: " << *ptr << std::endl;
std::cout << "Before modifyPointerValue ptr: " << ptr << std::endl;
modifyPointerValue(ptr);
std::cout << "After modifyPointerValue: " << *ptr << std::endl;
std::cout << "After modifyPointerValue ptr: " << ptr << std::endl;
std::cout << "Before modifyPointerReference: " << *ptr << std::endl;
std::cout << "Before modifyPointerReference ptr: " << ptr << std::endl;
modifyPointerReference(ptr);
std::cout << "After modifyPointerReference: " << *ptr << std::endl;
std::cout << "After modifyPointerReference ptr: " << ptr << std::endl;
return 0;
}
其中有一个错误,dangling_modifyPointerReference函数中产生了悬空指针,因为newValue只是一个局部变量,退出函数的时候,指针指向的内容已经没有了,需要在栈上创建一个变量,避免悬空指针的产生;