class X {
public:
X(int i) : num(i){}
int num;
};
void f(int i){
static X* px1 = new X(i);
X* px2 = new X(i);
cout<<px1->num;
cout<<px2->num<<' ';
};
void main(){
for (int i=0;i<5;i++)
f(i);
}
This code will output 00 01 02 03 04, but I don’t quite understand why static pointer px1 can’t change its value using operator new.
Also, this code has memory leakage problem. Can I use delete with px1? Will using delete on both pointers solve memory leakage problem?
That’s because static locals are initialized only once when control first passes through the initialization code. So although you call the function multiple times the following line:
will only be executed in the very first call (with
ibeing zero) and the variable will persist its value between the function calls.Yes, you can
deletepx1but you’d better set it to null afterwards to avoid double-free and undefined behavior. You also have leaks with objects pointed to bypx2– you have to take care of those objects too.