简体   繁体   English

静态指针和操作符新

[英]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 . 此代码将输出00 01 02 03 04 ,但我不太明白为什么静态指针px1无法使用operator new更改其值。

Also, this code has memory leakage problem. 此外,此代码有内存泄漏问题。 Can I use delete with px1 ? 我可以用px1 delete吗? Will using delete on both pointers solve memory leakage problem? 在两个指针上使用delete会解决内存泄漏问题吗?

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. 只会在第一次调用中执行( i为零),变量将在函数调用之间保持其值。

Yes, you can delete px1 but you'd better set it to null afterwards to avoid double-free and undefined behavior. 是的,您可以delete px1但最好将其设置为null,以避免双重自由和未定义的行为。 You also have leaks with objects pointed to by px2 - you have to take care of those objects too. 你也有px2指向的对象的泄漏 - 你也必须处理这些对象。

but I don't quite understand why static pointer px1 can't change its value using operator new 但我不太明白为什么静态指针px1不能使用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? 在两个指针上使用delete会解决内存泄漏问题吗?

Yes

As a better practice you should use std::unique_ptr instead of raw pointers and delete in this case. 作为一种更好的做法,你应该使用std::unique_ptr而不是原始指针并在这种情况下delete It does the delete for you automatically, so you won't leak. 它会自动为您执行delete ,因此您不会泄漏。

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: 通常,如果您希望对象在其创建的范围之外持久存在,则只使用new 。在这种情况下,您不需要它,因此您只需编写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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