unique_ptr
C++11中unique_ptr是用來取代auto_ptr的,就像其名字所表明的,它與所指對象的記憶體緊密綁定,不能與其他unique_ptr類型的指針對象共享所指對象的記憶體。比如下面的代碼是無法編譯通過的:
unique_ptr<int> up1(new int());
unique_ptr<int> up2 = up1; // 不能通過編譯
- 1
- 2
相比auto_ptr,這可以避免程式中誤用拷貝。當然,如果程式員确實希望使用auto_ptr那樣的轉移所有權操作,可以借助std::move來完成:
// Works, resource now stored in ptr2
unique_ptr<A> ptr2 = move(ptr1);
- 1
- 2
值得注意的是,如果unique_ptr作為函數的傳回值,下面的代碼會自動使用move語義而不會出現編譯錯誤:
unique_ptr<A> fun()
{
unique_ptr<A> ptr(new A);
/* ...
... */
return ptr;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
此外unique_ptr還增加了對數組的支援,是以在代碼中應該使用unique_ptr而不應該使用廢棄了的auto_ptr。