Hai*_*ang -1 c++ memory local-variables
我想知道变量在堆栈上的分配方式,所以我做了一个小的测试程序
#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;
}
Run Code Online (Sandbox Code Playgroud)
这是结果
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
Run Code Online (Sandbox Code Playgroud)
我们这里有两组变量
根据结果,我们知道G1已经在G2之前分配(可能是v_01 - > v_02 - > v_03 - > v_04).然而,有一些奇怪的事情:
为什么G1的地址更大G2,尽管在G2之前创建?
为什么每组中的变量都是连续分配的,但这些组彼此之间有点远?
为什么组中变量的地址与这些组之间的地址顺序相比具有不同的顺序?
在C(不确定C++,但我怀疑它是相似的),单独的对象的地址之间没有关系.该语言甚至没有定义它们的顺序关系; 在>
,<
,<=
,和>=
运营商对不指向同一数组的指针使用时,不确定的行为.
至于为什么对象最终会指向它们的指针的数字地址之间的特定关系,这纯粹是编译器的实现细节的结果,它取决于特定的编译器,编译器版本和使用的选项.
归档时间: |
|
查看次数: |
72 次 |
最近记录: |