2016-10-20 115 views
3

为什么我会用get()*,而不是仅仅调用*使用auto_ptr时,* ptr和* 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 

结果是完全一样的。 get()更安全吗?

+3

几乎没有区别。 – Nawaz

+7

因为它被标记为C++ 11:'std :: auto_ptr'已被弃用,并将在C++ 17中被删除。改为使用'std :: unique_ptr'。 –

+2

“是()更安全吗?”在我看来,使用'auto_ptr'会让你的整个代码不安全。不要使用它。 –

回答

6

实际上没有区别。

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

我希望能回答你的问题。现在我建议你避免使用std::auto_ptr,因为它设计不好—它甚至已被弃用,优先于其他智能指针,如std::unique_ptrstd::shared_ptr(连同std::weak_ptr)。

4

没有有效的区别。 operator*定义为返回*get()cppreference)。

您应该考虑在auto_ptr中使用unique_ptr。后者已经从当前的C++标准中删除,并具有非直观的拷贝行为。

5

*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_ptrshared_ptr代替。

0

不要在智能指针上使用get()(不管auto_,unique_,shared_或其他)。这将返回一个不受RAII类控制的裸指针。这样可以将指向另一个RAII类的指针(稍后会导致双重删除)或者调用者执行一些愚蠢的操作,如删除指针(再次导致双重删除)。只需解除智能指针的引用即可。

PS:仅限专家:是的,从智能指针中提取原始指针还有其他正当理由。但由于一般不使用get(),所以它被使用的时间成为“这里有些奇怪的事情正在发生,请注意!”的红旗。

相关问题