在未连续分配的函数中是否通过值变量和局部变量传递变量?

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)

我们这里有两组变量

  • 传递值变量的副本:v_01&v_02(G1)
  • 局部变量:v_03&v_04(G2)

根据结果​​,我们知道G1已经在G2之前分配(可能是v_01 - > v_02 - > v_03 - > v_04).然而,有一些奇怪的事情:

  • 每组中的每个变量都是连续分配的,但G1和G2似乎彼此相距很远,我认为它们应该都是0xbf9dd3a_或0xbf9dd37_或{0xbf9dd3ae - > 0xbf9dd3b1}或{0xbf9dd37e - > 0xbf9dd381}
  • G1的地址始终是G2的更大地址.我可以解释这个基于堆栈工作的方式和加载时程序的数据段.这是加载程序的数据段的快捷方式(来源:http://www.inf.udec.cl/~leo/teoX.pdf).

在此输入图像描述

  • 但是,如果我上面的解释是正确的,我无法解释为什么在每个组中,变量的地址都是基于它们的创建时间.(例如:v_04之前的v_03,所以v_04的地址大于v_03的地址)

为什么G1的地址更大G2,尽管在G2之前创建?

为什么每组中的变量都是连续分配的,但这些组彼此之间有点远?

为什么组中变量的地址与这些组之间的地址顺序相比具有不同的顺序?

R..*_*R.. 6

在C(不确定C++,但我怀疑它是相似的),单独的对象的地址之间没有关系.该语言甚至没有定义它们的顺序关系; 在>,<,<=,和>=运营商对不指向同一数组的指针使用时,不确定的行为.

至于为什么对象最终会指向它们的指针的数字地址之间的特定关系,这纯粹是编译器的实现细节的结果,它取决于特定的编译器,编译器版本和使用的选项.