微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用C智能指针?

我一直在使用C一段时间,我仍然对使用智能指针感到非常舒服,我只是在编辑一些使用它们的代码时使用它们,而不是在我自己的代码中(这可能值得说我是学生).

你能解释什么是智能指针的类型,它们如何工作以及何时使用它们?

此外,在其他人写的接口中接收或传递原始指针时,“协议”是什么?

谢谢.

解决方法

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?

对我而言,最重要的规则是:

>宪章资格>不要释放我没有分配的东西检查所有权/移动语义的转移

原文地址:https://www.jb51.cc/c/113224.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐