使用auto_ptr时*ptr和*ptr.get()之间有什么区别?

use*_*064 3 c++ smart-pointers auto-ptr

为什么要使用get()*,而不是只打电话*

请考虑以下代码:

auto_ptr<int> p (new int);
*p = 100;
cout << "p points to " << *p << '\n';           //100

auto_ptr<int> p (new int);
*p.get() = 100;
cout << "p points to " << *p.get() << '\n'; //100
Run Code Online (Sandbox Code Playgroud)

结果完全一样.是get()更安全?

Naw*_*waz 6

几乎没有区别.

在的情况下*p,所述过载operator*(由定义auto_ptr)被调用它返回参考到底层对象(解除引用它之后-这是由成员函数完成).但是,在后一种情况下,p.get()返回您自己取消引用的基础指针.

我希望能回答你的问题.现在我建议你避免使用std::auto_ptr,因为设计很糟糕 - 它甚至已被弃用,优先于其他智能指针,如std::unique_ptrstd::shared_ptr(以及 std::weak_ptr).


was*_*ful 5

*p调用auto_ptr::operator*,取消引用托管指针.

*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
Run Code Online (Sandbox Code Playgroud)

要避免此问题,您必须"管理托管指针":

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
Run Code Online (Sandbox Code Playgroud)

使用unique_ptrshared_ptr代替.