當你拷貝一個auto_ptr時,它所指向的對象的所有權被移交到拷入的auto_ptr上,而它自身被置爲NULL。我的理解是:拷貝一個auto_ptr意味着改變它的值。例如:
auto_ptr<int> pint1(new int);//pint1指向一個int
auto_ptr<int> pint2(pint1);//pint2指向pint1的int;pint1被置爲NULL
pint1 = pint2;//現在pint1又指向int了;pint2被置爲NULL
在看一種實現sort的方法:
template<class RandomAccessIterator, classCompare>
void sort(RandomAccessIterator first,RandomAccessIteratorlast,Compare comp)
{
typedeftypename iterator_traits<RandomAccessIterator>::value_type ElementType;
RandomAccessIterator i;
… //使i指向基準元素
ElementType pivotValue(*i);//把基準元素拷貝到局部臨時變量中
…
}
vector<auto_ptr<int>>ints;
…
sort(ints.begin(),ints.end(),greater());
當我們使用iterator_traits<RandomAccessIterator>::value_type時,必須在它的前面加上typename,因爲它是由模板參數來決定的類型名,在這個例子中,參數是RandomAccessIterator。
上面的代碼中有問題的語句是:
ElementType pivotValue(*i);
因爲它把一個元素從被排序的區間中拷貝到一個臨時對象中。在我們這個例子中,該元素是一個auto_ptr<int>,所以這一操作悄悄地把被拷貝的auto_ptr---就是在vector中的那個置爲NULL。更嚴重的是,當pivotValue的作用域結束時,它會自動刪除自己所指向的int。因此,當對sort的調用返回時,vector中的內容已經被改變了,至少有一個int都被刪除了。
千萬別創建包含auto_ptr的容器。