![](/img/trans.png)
[英]How to get the memory address of an object with `this` reference inside the class in C++
[英]How reference share the memory address
我在讀什么區別的B / W在C指針變量和引用變量++ 這里的 。 我得到了一點, 而引用共享相同的內存地址,但也占用了堆棧上的一些空間。 。 它共享相同的地址空間是什么意思。請清楚說明如何在c ++中實現引用。
這是一個有點令人困惑的答案。 但這意味着相當簡單的事情。 關於占用堆棧空間的部分僅僅意味着引用實際占用內存。 也就是說,它占用與指針相同的內存量(並且在每個C ++實現中[我知道]它是通過使用實際指針實現的)。
關於“共享相同內存地址”的部分實際上意味着引用不是可獨立尋址的值。 如果你有一個指向某個東西的指針,你可以獲取該指針的地址,最后得到指向某個東西的指針。 但是,如果您對某些內容有引用,則無法獲取該引用的地址。 試圖這樣做實際上需要引用的東西的地址。 這就是他所說的“共享相同的內存地址”。
Roghly說,引用變量就像一個看起來不像指針的指針變量(即沒有用於訪問內容的指針語法)。 這不需要對Stack或Heap做任何事情。
int i = 5; // integer on the Stack
int * j = new int (5); // integer on the Heap (accessible through pointer, naturally)
int & iref = i; // reference to integer on the Stack
int & jref = *j; // reference to integer on the Heap
int * ipointer = & i; // pointer to integer on the Stack
int * jpointer = j; // pointer to integer on the Heap
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.