我想知道变量在堆栈上的分配方式,所以我做了一个小的测试程序
#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 - &gt; v_02 - &gt; v_03 - &gt; v_04)。然而,有一些奇怪的事情:
为什么G1的地址大于G2,尽管是在G2之前创建的?
为什么每组中的变量都是连续分配的,但这些组彼此之间有点远?
为什么组中变量的地址与这些组之间的地址顺序有不同的顺序?
答案 0 :(得分:6)
在C中(不确定C ++,但我怀疑它类似),单独对象的地址之间没有关系。语言甚至没有定义关于它们的订单关系; subscriber
,>
,<
和<=
运算符在未指向同一数组的指针上使用时具有未定义的行为。
至于为什么对象最终会指向它们的指针的数字地址之间的特定关系,这纯粹是编译器的实现细节的结果,它取决于特定的编译器,编译器版本和使用的选项。
答案 1 :(得分:3)
它依赖编译器而不是标准的一部分。编译器决定数据需要多少内存,为该数据保留内存块,并决定如何分配它。