2009-05-15 4 views
7
#include <boost/ptr_container/ptr_vector.hpp> 
#include <iostream> 

using namespace std; 
using namespace boost; 

struct A { 
    ~A() { cout << "deleted " << (void*)this << endl; } 
}; 

int main() { 
    ptr_vector<A> v; 
    v.push_back(new A); 
    A *temp = &v.front(); 
    v.release(v.begin()); 
    delete temp; 
    return 0; 
} 

出力:boost :: ptr_vectorの要素の所有権をどのように譲渡しますか?

deleted 0x300300 
deleted 0x300300 
c(6832) malloc: *** error for object 0x300300: double free 

答えて

15

ptr_vector<A>::releaseauto_type項目がスコープの外に出るときに軽量スマートポインタの一種である、ptr_vector<A>::auto_typeを返し、それを指すものです自動的に削除されます。事に生のポインタを回復し、それを保持してauto_ptrによって削除されてからそれを維持するには、あまりにもその上releaseを呼び出す必要があります:

int main() { 
    ptr_vector<A> v; 
    v.push_back(new A); 
    A *temp=v.release(v.begin()).release(); 
    delete temp; 
    return 0; 
} 

最初releaseそれを放棄するptr_vectorに指示します。秒はauto_ptrにもそれをあきらめます。

+0

ありがとう、感謝します。 –

関連する問題