簡體   English   中英

C++ 傳遞 const 參考語法

[英]C++ Pass by const reference syntax

我知道通過引用傳遞與通過指針傳遞的主題被大量覆蓋......我很確定我理解了所有細微差別,直到我讀到這個:

http://carlo17.home.xs4all.nl/cpp/const.qualifier.html

內容為(以防鏈接失效)

The prototype for foobar can have any of the following footprints:
void foobar(TYPE);      // Pass by value
void foobar(TYPE&);     // Pass by reference
void foobar(TYPE const&);   // Pass by const reference

Note that I put the const to the right of TYPE because we don't know if TYPE (this is not a template parameter, but rather for instance a literal char*) is a pointer or not!

作者的意思是“請注意,我將 const 放在 TYPE 的右側,因為我們不知道 TYPE ... 是否是指針!”

我讀到的關於這個主題的所有內容都一致地說:

void foodbar(TYPE const &)

也等價

void foobar(const TYPE &)

如果我正確理解了作者,他/她是在說:

const int *X vs int * const X where 指針,X 本身是 const 而 X 指向的是 const?

如果是這樣,這是真的嗎?

如果 TYPE 是int*之類的#define ,則const的位置確實很重要。 在這種情況下,您將獲得const int*int* const ,具體取決於const的位置。

如果 TYPE 是 typedef 或模板參數,則const將影響整個類型。

對我來說,這看起來更像是反對宏的另一個論點,而不是需要在聲明中使用某種特定樣式。

查看C++ FAQ Lite (如文章所示),您從右到左閱讀指針聲明。 因此,如果 TYPE 是指針,則 * 的位置確實會有所不同。 點擊鏈接查看完整故事。

void foobar(TYPE const&);   // Pass by const reference

如果 TYPE 是指向類型 ABC 的指針,則

void foobar(ABC* const&)

不同於

void foobar(const ABC* &)

我相信這就是作者的全部內容。

編輯

如果 typedef 是指針,這也適用

typedef SomeStruct* pSomeStruct;
void foobar(pSomeStruct* const &); // const reference to a pointer
                                   // to a pointer to SomeStruct
void foobar(const pSomeStruct* &); // reference to a pointer
                                   // to a const pointer to const SomeStruct

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM