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->showaddress
和a->setvalue
依然可以正常调用?
PHP中文网2017-04-17 13:00:36
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).