简体   繁体   中英

Static pointer and operator new

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:

static X* px1 = new X(i);

will only be executed in the very first call (with i being zero) and the variable will persist its value between the function calls.

Yes, you can delete px1 but you'd better set it to null afterwards to avoid double-free and undefined behavior. You also have leaks with objects pointed to by px2 - you have to take care of those objects too.

but I don't quite understand why static pointer px1 can't change its value using operator new

Static locals are initialized the first time they are called, and only the first time

Will using delete on both pointers solve memory leakage problem?

Yes

As a better practice you should use std::unique_ptr instead of raw pointers and delete in this case. It does the delete for you automatically, so you won't leak.

Additionally neither of your allocations needs to be allocating on the heap. Normally you only use new if you want an object to persist outside of the scope it's created in. In this case, you don't need it to so you could just write:

static X x1(i);
X x2(i);
cout<<x1.num;
cout<<x2.num<<' ';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM