*p
調用auto_ptr::operator*
,它取消引用託管指針。
*p.get
*p.get
首先調用方法auto_ptr::get
,它返回託管指針,然後由操作員*
取消引用。
這些將在執行完成後提供完全相同的結果:託管指針被解除引用,並且在使用get
時不會有額外的檢查。
請注意auto_ptr
自C++ 11以來已棄用。複印時,這是危險的,因爲指針的所有權轉移:
std::auto_ptr<int> p(new int(42));
{
std::auto_ptr<int> copy_of_p(p); // ownership of *p is transfered here
} // copy_of_p is destroyed, and deletes its owned pointer
// p is now a dangling pointer
爲了避免這個問題,你不得不「管理管理指針」:
std::auto_ptr<int> p(new int(42));
{
std::auto_ptr<int> copy_of_p(p); // ownership of *p is transfered here
// ...
p = copy_of_p; // p gets back ownership
} // copy_of_p is destroyed, but doesn't delete pointer owned by p
// p is still valid
使用unique_ptr
或shared_ptr
代替。
幾乎沒有區別。 – Nawaz
因爲它被標記爲C++ 11:'std :: auto_ptr'已被棄用,並將在C++ 17中被刪除。改爲使用'std :: unique_ptr'。 –
「是()更安全嗎?」在我看來,使用'auto_ptr'會讓你的整個代碼不安全。不要使用它。 –