在C ++中,对传递给函数的指针的更改是否反映在调用函数中? [英] In C++, are changes to pointers passed to a function reflected in the calling function?

查看:101
本文介绍了在C ++中,对传递给函数的指针的更改是否反映在调用函数中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将指针P从函数f1传递到函数f2,并修改f2中P的内容,这些修改是否会自动反映在f1中?

If I pass a pointer P from function f1 to function f2, and modify the contents of P in f2, will these modifications be reflected in f1 automatically?

例如,如果我需要删除链表中的第一个节点:

For example, if I need to delete the first node in a linked list:

void f2( Node *p)
{
    Node *tmp = p;
    p = p -> next;
    delete tmp;
}

对P所做的更改会反映在调用函数中,还是现在指向已释放的内存空间?

Will the changes made to P be reflected in the calling function, or will it now point to a memory space that has been deallocated?

(我的直觉回答是否,更改不会反映出来.但是,良好的消息来源告诉我,上面的代码将起作用.有人可以花时间给出答案并解释其背后的原因吗?此外,如果上面的代码有错误,如何在不使用返回类型的情况下实现此目标?)

( My intuitive answer here is no, changes are not reflected. However, good sources tell me that the above code will work. Can someone take the time to give the answer and explain the reasoning behind it also please? Also, if the above code is faulty, how can we achieve this without using a return type? )

推荐答案

如果我将指针P从函数f1传递到函数f2,并修改f2中P的内容,这些修改是否会自动反映在f1中?

If I pass a pointer P from function f1 to function f2, and modify the contents of P in f2, will these modifications be reflected in f1 automatically?

不.由于C和C ++实现了按值传递,因此指针的值在传递给函数时会被复制.只会修改该本地副本,并且在保留该功能时不会将该值复制回(这是几种语言支持的按引用复制).

No. Since C and C++ implement pass-by-value, the value of the pointer is copied when it’s passed to the function. Only that local copy is modified, and the value is not copied back when the function is left (this would be copy-by-reference which a few languages support).

如果要修改原始值,则需要将引用传递给指针,即将f2的签名更改为:

If you want the original value to be modified, you need to pass a reference to the pointer, i.e. change your signature of f2 to read:

void f2( Node*& p)

但是,您的f2不仅更改了指针p,而且还使用delete更改了其基础值(=指向的值). 更改确实对呼叫者可见.

However, your f2 not only changes the pointer p, it also changes its underlying value (= the value being pointed to) by using delete. That change is indeed visible to the caller.

这篇关于在C ++中,对传递给函数的指针的更改是否反映在调用函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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