[英]Are variables for pass by value variables and local variables in a function not allocated continuously?
我想知道變量在堆棧上的分配方式,所以我制作了一個小型測試程序
#include <iostream>
#include <stdlib.h>
using namespace std;
class test
{
public:
test()
{
}
test(const test &obj)
{
cout << "a clone of test has been created" << endl;
}
};
void foo(test variable_01, test variable_02)
{
cout << "v3 and v4 have not been created" << endl;
char variable_03;
char variable_04;
cout << "v3 and v4 have been created" << endl;
cout << "Adrress of variable 01: " << static_cast<void*>(&variable_01) << endl;
cout << "Adrress of variable 02: " << static_cast<void*>(&variable_02) << endl;
cout << "Adrress of variable 03: " << static_cast<void*>(&variable_03) << endl;
cout << "Adrress of variable 04: " << static_cast<void*>(&variable_04) << endl;
}
int main()
{
test temp;
foo(temp,temp);
return 0;
}
這是結果
a clone of test has been created
a clone of test has been created
v3 and v4 have not been created
v3 and v4 have been created
Adrress of variable 01: 0xbf9dd3ae
Adrress of variable 02: 0xbf9dd3af
Adrress of variable 03: 0xbf9dd37e
Adrress of variable 04: 0xbf9dd37f
我們這里有兩組變量
根據結果,我們知道G1已分配在G2之前(也許是v_01-> v_02-> v_03-> v_04)。 但是有一些奇怪的事情:
盡管在G2之前創建了地址,但為什么G1的地址大於G2?
為什么每個組中的變量都是連續分配的,但是這些組之間的距離有點遠?
為什么組中變量的地址與這些組之間的地址順序相比具有不同的順序?
在C語言中(不確定C ++,但我懷疑它是相似的),獨立對象的地址之間沒有關系。 該語言甚至沒有定義它們之間的順序關系。 >
, <
, <=
和>=
運算符在未指向同一數組的指針上使用時具有未定義的行為。
至於為什么對象最終在指向它們的指針的數字地址之間具有特定的關系,這純粹是編譯器實現細節的結果,它取決於特定的編譯器,編譯器版本和使用的選項。
它依賴於編譯器,而不是標准的一部分。 編譯器決定數據將需要多少內存,為該數據保留內存塊,並決定如何分配它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.