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

时间:2016-07-24 19:16:50

标签: 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;
}

这是结果

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

我们这里有两组变量

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

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

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

enter image description here

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

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

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

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

2 个答案:

答案 0 :(得分:6)

在C中(不确定C ++,但我怀疑它类似),单独对象的地址之间没有关系。语言甚至没有定义关于它们的订单关系; subscriber><<=运算符在未指向同一数组的指针上使用时具有未定义的行为。

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

答案 1 :(得分:3)

它依赖编译器而不是标准的一部分。编译器决定数据需要多少内存,为该数据保留内存块,并决定如何分配它。