問題描述
在 C++ 中傳遞指針參數(shù),按值傳遞嗎?因?yàn)槲铱吹綄?duì)指針的任何更改都不會(huì)反映在方法之外.我通過取消引用指針?biāo)龅母臅?huì)得到反映.
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.
在這種情況下,使用指向指針的指針作為函數(shù)的參數(shù)來修改函數(shù)內(nèi)的指針值是否可以接受/標(biāo)準(zhǔn)程序?
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?
推薦答案
是的.
指針與其他任何東西一樣按值傳遞.這意味著指針變量的內(nèi)容(指向的對(duì)象的地址)被復(fù)制.這意味著如果您更改函數(shù)體中指針的值,該更改將不會(huì)反映在仍指向舊對(duì)象的外部指針中.但是你可以改變指向的對(duì)象的值.
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.
如果要將指針?biāo)龅母姆从车酵獠恐羔?使其指向其他內(nèi)容),則需要兩個(gè)間接級(jí)別(指向指針的指針).當(dāng)調(diào)用函數(shù)時(shí),它是通過在指針名稱之前放置一個(gè) &
來完成的.這是標(biāo)準(zhǔn)的 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++ 時(shí),使用引用優(yōu)于指針(此后也使用指向指針的指針).
When using C++, using references is preferred to pointer (henceforth also to pointer to pointer).
對(duì)于為什么引用應(yīng)該優(yōu)先于指針,有幾個(gè)原因:
For the why references should be preferred to pointers, there is several reasons:
- 引用比函數(shù)體中的指針引入更少的語法噪音
- 引用保存的信息比指針多,對(duì)編譯器有用
引用的缺點(diǎn)主要是:
- 它們打破了 C 的簡(jiǎn)單的按值傳遞規(guī)則,是什么讓理解函數(shù)關(guān)于參數(shù)的行為(它們會(huì)被改變嗎?)不太明顯.您還需要函數(shù)原型來確定.但這并不比使用 C 時(shí)所需的多個(gè)指針級(jí)別更糟糕.
- C 不支持它們,當(dāng)您編寫的代碼應(yīng)適用于 C 和 C++ 程序時(shí),這可能會(huì)成為一個(gè)問題(但這不是最常見的情況).
在指針到指針的特定情況下,區(qū)別主要是簡(jiǎn)單,但使用引用可能也很容易刪除兩級(jí)指針,只傳遞一個(gè)引用而不是指向指針的指針.
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.
這篇關(guān)于在 C++ 中傳遞指針參數(shù),按值傳遞嗎?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!