2016-04-11 134 views
0

下面的代碼導致運行時錯誤。顯然,當unique_ptra超出範圍時,它會嘗試刪除已被刪除的內存,因此會導致堆問題。我的問題是我在X行應該做什麼更改,因爲它們共享相同的內存,並且即使在使用delete調用之後也不會有任何運行時錯誤。運行時錯誤與unique_ptr

#include <iostream> 
#include <memory> 
using namespace std; 
int main() 
{ 
    int* p = new int (10); 
    unique_ptr<int> a (p); // Line X 
    delete p; 
    return 0; 
}   

回答

2

線X,你轉移標的物的所有權由p所創建的unique_ptr<int> a指出。您以後不應該明確刪除它,否則會出現雙重刪除錯誤。

如果你不希望unique_ptr刪除它指向的對象,你應該考慮在銷燬前釋放它,例如:

int main() { 
    int * p = new int(10); 
    unique_ptr<int> a(p); 
    a.release(); // <--- Release ownership of the integer 
    // unique_ptr a no longer "owns" the integer 
    delete p; 
} 

unique_ptr整個的一點是,它「擁有」和對象,以RAII方式釋放其資源。

0

與C++ 14起,您的代碼段可被確定如下:

#include <iostream> 
#include <memory> 
using namespace std; 
int main() 
{ 
    auto a = make_unique<int>(10); // = unique_ptr<int>(new int(10)) 
    return 0; 
}