【发布时间】:2011-05-08 08:17:43
【问题描述】:
我以为我的 C++ 相当好,但事实证明我不是。我之前问的一个问题:C++ const lvalue references 在其中一个答案中有以下代码:
#include <iostream>
using namespace std;
int& GenX(bool reset)
{
static int* x = new int;
*x = 100;
if (reset)
{
delete x;
x = new int;
*x = 200;
}
return *x;
}
class YStore
{
public:
YStore(int& x);
int& getX() { return my_x; }
private:
int& my_x;
};
YStore::YStore(int& x)
: my_x(x)
{
}
int main()
{
YStore Y(GenX(false));
cout << "X: " << Y.getX() << endl;
GenX(true); // side-effect in Y
cout << "X: " << Y.getX() << endl;
return 0;
}
以上代码输出 X: 100, X:200。我不理解为什么。 我玩了一下,并添加了更多输出,即删除 x 之前的 cout;和新的 x 之后的 cout;在复位控制块内。
我得到的是: 删除前:0x92ee018 新后:0x92ee018
所以,我认为 static 正在默默地更新 x 失败,而第二个 getX 正在使用(在删除之后)未初始化的内存;为了测试这一点,我添加了 x = 0;在 delete 之后,new 之前,以及另一个 cout 以确保 x 确实重置为 0。它是。
那么,这里发生了什么?为什么 new 返回的内存块与之前的 delete 应该释放的内存块完全相同?这仅仅是因为这是操作系统的内存管理器决定做的事情,还是我缺少静态的一些特别之处?
谢谢!
【问题讨论】:
-
虽然您的问题最终归结为静态以外的其他问题,但有4 different meanings of static。
标签: c++ memory-management static