Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 堆栈内存由动态分配的对象成员变量引用_C++_Visual Studio 2008 - Fatal编程技术网

C++ 堆栈内存由动态分配的对象成员变量引用

C++ 堆栈内存由动态分配的对象成员变量引用,c++,visual-studio-2008,C++,Visual Studio 2008,我有以下代码 class Test { public: int &ref; int a; Test(int &x) :ref(x) { cout<<"Address of reference "<<&ref<<endl; cout<<"&a : "<<&a<<endl; cout<&

我有以下代码

class Test
{
public:
    int &ref;
    int a;

    Test(int &x)
        :ref(x)
    {
        cout<<"Address of reference "<<&ref<<endl;
        cout<<"&a : "<<&a<<endl;
        cout<<"this = "<<this<<endl;
    }
};

int main()
{
    Test *pObj = NULL;
    {
        int i = 10;
        cout<<"Address of referent "<<&i<<endl;
        pObj = new Test(i);
    }
    pObj->ref++;
    cout<<pObj->ref;
}
如您所见,测试对象是动态创建的。存储在堆栈上的变量i作为参数发送给测试类的构造函数。我打印了变量I、ref和a的地址

问题:一旦程序控制退出声明它的块,变量i将被销毁。但动态分配对象的成员变量ref仍将引用堆栈地址(i的地址)。能够在i死后使用ref

为什么堆对象引用堆栈内存?为什么允许这样做

为什么堆对象有对堆栈内存的引用

由于您通过引用将局部变量
i
传递到动态创建的
Test
对象的构造函数中,因此构造函数存储了该引用

为什么允许这样做

在C++中,程序员负责确保使用的指针指向有效对象。这种语言没有任何保护措施来“保护”您不做这种愚蠢的事情(当然,有一些好的编程实践可以帮助您确保您编写的代码不应该出现这样的问题)


试图在对象的生命周期结束后使用该对象会导致未定义的行为。

让我们知道cout的输出是什么
Address of referent 002DFB3C

Address of reference 002DFB3C

&a : 00734C94

this = 00734C90