在 C++ 中传递指针参数,按值传递吗?因为我看到对指针的任何更改都不会反映在方法之外.我通过取消引用指针所做的更改会得到反映.
Is passing pointer argument, pass by value in C++? Since i see that any change to the pointer as such is not reflected outside the method. The changes i do by dereferencing the pointer is reflected though.
在这种情况下,使用指向指针的指针作为函数的参数来修改函数内的指针值是否可以接受/标准程序?
In that case, is it acceptable/standard procedure to use pointer to pointer as argument to a function to modify the pointer value as such within a function?
是的.
指针与其他任何东西一样按值传递.这意味着指针变量的内容(指向的对象的地址)被复制.这意味着如果您更改函数体中指针的值,该更改将不会反映在仍指向旧对象的外部指针中.但是你可以改变指向的对象的值.
Pointers are passed by value as anything else. That means the contents of the pointer variable (the address of the object pointed to) is copied. That means that if you change the value of the pointer in the function body, that change will not be reflected in the external pointer that will still point to the old object. But you can change the value of the object pointed to.
如果要将指针所做的更改反映到外部指针(使其指向其他内容),则需要两个间接级别(指向指针的指针).当调用函数时,它是通过在指针名称之前放置一个 &
来完成的.这是标准的 C 语言做事方式.
If you want to reflect changes made to the pointer to the external pointer (make it point to something else), you need two levels of indirection (pointer to pointer). When calling functions it's done by putting a &
before the name of the pointer. It is the standard C way of doing things.
在使用 C++ 时,使用引用优于指针(此后也使用指向指针的指针).
When using C++, using references is preferred to pointer (henceforth also to pointer to pointer).
对于为什么引用应该优先于指针,有几个原因:
For the why references should be preferred to pointers, there is several reasons:
引用的缺点主要是:
在指针到指针的特定情况下,区别主要是简单,但使用引用可能也很容易删除两级指针,只传递一个引用而不是指向指针的指针.
In the specific case of pointer to pointer, the difference is mostly simplicity, but using reference it may also be easy to remove both levels of pointers and pass only one reference instead of a pointer to pointer.
这篇关于在 C++ 中传递指针参数,按值传递吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!