2014-12-10 73 views
-6

樣品在這裏:此代碼中的內存泄漏?

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; 
} 

誰能幫助我?這段代碼有什麼問題?內存泄漏?或者是其他的錯誤?

+10

是的,顯然。你有一個沒有匹配delete的'new'。 – 2014-12-10 22:21:19

+3

內存泄漏應該是您最擔心的問題。這段代碼甚至沒有編譯。 – 0x499602D2 2014-12-10 22:21:49

+3

如果它不編譯,它不會泄漏,是嗎? – 2014-12-10 22:27:22

回答

1
從問題

除了在評論中指出,應該(用new關鍵字)創造出你在堆上分配的項目要求delete[]析構函數:

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之後,因爲它是一個數組。

+3

這仍然不會編譯。數組不可分配。 – 0x499602D2 2014-12-10 22:27:10

+0

@ 0x499602D2,好吧,tigerrussell說:「從評論中指出的問題來看......」 – kay 2014-12-10 22:28:08

+0

@Kay評論中沒有指出其他具體問題。 OP不知道數組是不可分配的。 – 0x499602D2 2014-12-10 22:29:51

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,這將解決您的內存泄漏問題。