*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'会让你的整个代码不安全。不要使用它。 –