問題描述
在 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:
- 引用比函數體中的指針引入更少的語法噪音
- 引用保存的信息比指針多,對編譯器有用
引用的缺點主要是:
- 它們打破了 C 的簡單的按值傳遞規則,是什么讓理解函數關于參數的行為(它們會被改變嗎?)不太明顯.您還需要函數原型來確定.但這并不比使用 C 時所需的多個指針級別更糟糕.
- C 不支持它們,當您編寫的代碼應適用于 C 和 C++ 程序時,這可能會成為一個問題(但這不是最常見的情況).
在指針到指針的特定情況下,區別主要是簡單,但使用引用可能也很容易刪除兩級指針,只傳遞一個引用而不是指向指針的指針.
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++ 中傳遞指針參數,按值傳遞嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!