内存泄漏在这段代码中?

时间:2014-12-10 22:20:41

标签: c++

此处示例:

class A
{
private:
    int buff[1000];
public:
    A(int n)
    {
        buff = new int[n];
    }
};

 int main()
 {
     for (int i = 10; i < 1000; i++)
     {
         A a(i);
     }
     return 0;
 }

任何人都可以帮助我吗?这段代码有什么问题?内存泄漏?还是其他任何错误?

2 个答案:

答案 0 :(得分:1)

除了注释中指出的问题之外,你应该创建一个析构函数,它在你在堆上分配的项目上调用delete[](使用new关键字):

class A{
   private:
       int buff[1000];
   public:
       A(int n){
           buff=new int[n];
       }
       ~A() {
           delete[] buff;
       }
};

int main(){
    for(int i=10;i<1000;i++){
        A a(i);
     }   
     return 0;
}

不要忘记[]之后的delete,因为它是一个数组。

答案 1 :(得分:0)

现代C ++说你应该在你的代码中使用newdelete,而是std::unique_ptr为你做内存管理。

因此,你的班级将以这种方式更好地适应现代习语:

#include <memory>

class A
{
private:
    std::unique_ptr<int[]> buff;
public:
    A(int n)
        : buff(std::make_unique(int[n])) // buff(new int[n]) if using C++11
    { }
};

int main()
{
    A a(5);
    return 0;
}

不幸的是,std::make_unique在C ++ 11中不可用,因此在此之前您必须使用new。但是,您仍然可以使用std::unique_ptr,这将解决您的内存泄漏问题。

相关问题