c++中成员变量为引用
迷茫
迷茫 2017-04-17 12:58:36
0
1
641
class A {
private:
    int&a;
public:
    A(int b):a(b){}
    void showaddress() {
        cout<<"address: "<<&a<<endl;
    }
    void setvalue() {
        a = 3;
    }
    void show() {
        cout<<a<<endl;
    }
};

int main(void) {
    int b = 1;
    A*a = new A(b);
    a->showaddress();
    a->setvalue();
    a->show();
    return 0;
}

问题:
在初始化类A中的成员变量int&a时,用的是一个临时变量。在离开A构造函数后,这个临时变量已经释放,为什么之后的a->showaddressa->setvalue依然可以正常调用?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
Ty80

The b passed to the constructor is indeed a temporary variable, it might as well be called b'. However, b' also has a location in memory. Although the life cycle of b' is over, its mission has been completed - let a "point" to the memory address where b' is located (that is, the return value of the function showaddress), or in other words, to where b' is (or where it once was). memory location) has a new name a. Therefore, the "life" of b' is "continued" through a. . . This memory may not have been reallocated yet (according to the principle of locality of the program, it is generally not allocated immediately), and you can scribble in it (for example, calling the function setvalue).

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!