2016-04-11 1 views
0

以下のコードは実行時エラーを引き起こします。明らかにunique_ptraが有効範囲外になると、既に削除されているメモリを削除しようとするため、ヒープの問題が発生します。私の質問は、同じメモリを共有し、deleteコールを使用した後でもランタイムエラーが発生しないため、行Xで強調表示する必要がある変更点です。ラインX上で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

、あなたは、オブジェクトの所有権を移転している作成unique_ptr<int> aからpで指されます。後で明示的に削除しないでください。削除しないと、二重削除エラーが発生します。

あなたは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方式で解放します。次のようにC++ 14で開始

0

は、あなたのスニペットを固定することができる。

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