简体   繁体   English

删除在析构函数中不起作用?

[英]delete doesn't work in destructor?

I have a problem deleting class attributes inside the destructor of the class, if I try to do the same thing in a classic procedural program it works perfectly. 我在类的析构函数中删除类属性时遇到问题,如果我尝试在经典程序程序中执行相同的操作,则它可以完美地运行。

But if I try to execute the code below the destructor doesn't delete "array" and doesn't free the memory: 但是,如果我尝试执行下面的代码,析构函数不会delete “数组”并且不释放内存:

class MyClass
{
private:
    int *array;
    int n = 2000000;
public:
    MyClass(){
        this->array = new int[n];
        for(int i=0; i<n; i++){
            array[i] = i;
        }
    }
    ~MyClass(){
        delete[] array;
    }
};


int main(int argc, const char * argv[])
{
    MyClass *test = new MyClass;

    delete test;

    return 0;
}

Why? 为什么?

**别担心!**(我应该说_'不要惊慌失措'?)

If the delete statement in the destructor of your class is executed, the memory allocated in the constructor will be released and available for future use. 如果执行类的析构函数中的delete语句,则构造函数中分配的内存将被释放并可供将来使用。

This doesn't inherently mean that the memory allocated by the OS for the actual process that instantiates your class will be reduced. 这本身并不意味着操作系统为实例化您的类的实际进程分配的内存将减少。

As an additional hint: To detect 'real' memory leaks in your programs, use a suitable tool like Valgrind or alike. 作为附加提示:要检测程序中的“真实”内存泄漏,请使用Valgrind或类似工具。

When you allocate memory with new or malloc and free it afterwards, it doesn't neccessarily mean, that the memory is returned to the operating system. 当您使用new或malloc分配内存并在之后释放它时,并不一定意味着内存将返回到操作系统。 The implementation can keep the memory and subsequent calls to malloc or new can make use of this memory to avoid the overhead of allocating memory from the OS again. 实现可以保持内存和后续对malloc或new的调用可以利用这个内存来避免再次从OS分配内存的开销。

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

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