我已经使用 C++ 一段时间了,但我仍然对使用智能指针感到不太舒服,而且我只是在编辑一些使用它们的代码时才使用它们,从来没有在我自己的代码中使用它们(它可能值得说我是一名学生)。
您能解释一下智能指针的类型、它们的工作原理以及何时使用它们吗?
另外,在其他人编写的接口(interface)中接收或传递原始指针时的“协议(protocol)”是什么?
谢谢。
最佳答案
C++98 不提供除auto_ptr
之外的任何智能指针。这充满了自己的问题。 C++0X 试图通过引入更多变体(shared_ptr
、unique_ptr
等)来解决这个问题。与此同时,最好的选择是使用 Boost。看看你可以选择的各种口味here . Boost 由社区驱动,经过广泛测试,当然是免费的。包含示例代码的优秀文档可帮助您入门。
Can you explain what are the types of smart pointers, how do they work and when to use them?
有很多。简而言之:
scoped_ptr
<boost/scoped_ptr.hpp>
Simple sole ownership of single objects. Noncopyable.
scoped_array
<boost/scoped_array.hpp>
Simple sole ownership of arrays. Noncopyable.
shared_ptr
<boost/shared_ptr.hpp>
Object ownership shared among multiple pointers.
shared_array
<boost/shared_array.hpp>
Array ownership shared among multiple pointers.
weak_ptr
<boost/weak_ptr.hpp>
Non-owning observers of an object owned by shared_ptr.
intrusive_ptr
<boost/intrusive_ptr.hpp>
Shared ownership of objects with an embedded reference count.
(这是来自 Boost 文档,请注意它们也有此类指针的容器!)
Also, what is the "protocol" when receiving or passing raw pointers in interfaces written by other people?
对我来说最重要的规则是:
- Const-资格
- 不要取消分配我没有分配的东西
- 检查所有权转移/移动语义
关于c++ - 如何使用 C++ 智能指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3484123/