加速 C++:我可以用原始指针替换智能指针吗?
我喜欢这本书,遗憾的是它没有涵盖智能指针,因为它们不是当时标准的一部分。那么,在阅读这本书时,我可以用智能指针分别引用来公平地替换每个提到的指针吗?
I love this book, sadly it does not cover smart pointers as they were not part of the standard back then. So when reading the book can I fairly substitute every mentioned pointer by a smart pointer, respectively reference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
“智能指针”有点用词不当。 “聪明”的部分是,他们会为你做一些事情,无论你是否需要、想要,甚至是否理解这些事情是什么。这真的很重要。因为有时您想去商店,智能指针会 开车送你去教堂。智能指针解决了一些非常具体的问题。许多人会认为,如果您认为需要智能指针,那么
"Smart Pointer" is a bit of a misnomer. The "smart" part is that they will do some things for you, whether or not you need, want, or even understand what those things are. And that's really important. Because sometimes you'll want to go to the store, and smart pointers will drive you to church. Smart pointers solve some very specific problems. Many would argue that if you think you need smart pointers, then you're probably solving the wrong problem. I personally try not to take sides. Instead, I use a toolbox metaphor - you need to really understand the problem you're solving, and the tools that you have at your disposal. Only then can you remotely expect to select the right tool for the job. Best of luck, and keep questioning!
嗯,有不同类型的智能指针。例如:
您可以创建一个
scoped_ptr
类,当您在代码块内分配任务并且您希望资源在超出范围时自动释放时,该类会很有用。类似于:
此外,您可以创建一个行为相同但保留引用计数的
shared_ptr
。一旦引用计数达到 0,您就释放分配。shared_ptr
对于存储在 STL 容器等中的指针非常有用。所以是的,您可以使用智能指针来实现程序的大部分目的。
但请明智地考虑您需要哪种智能指针以及原因。
不要简单地“查找并替换”您遇到的所有指针。
Well, there are different kinds of smart pointers. For example:
You could create a
scoped_ptr
class, which would be useful when you're allocating for a task within a block of code, and you want the resource to be freed automatically when it runs of of scope.Something like:
Additionally you could create a
shared_ptr
who acts the same but keeps a ref count. Once the ref count reach 0 you deallocate.shared_ptr
would be useful for pointers stored in STL containers and the like.So yes, you could use smart pointers for most of the purposes of your program.
But think judiciously about what kind of smart pointer you need and why.
Do not simply "find and replace" all the pointers you come across.
不可以。
代表对象所有权的指针应该被智能指针取代。
其他指针应该用迭代器替换(在最简单的情况下,迭代器只是原始指针的 typedef,但没有人会认为它们需要删除)。
当然,智能指针和迭代器的实现代码将继续需要原始指针。
No.
Pointers which represent object ownership should be replaced by smart pointers.
Other pointers should be replaced by iterators (which in the simplest case is just a
typedef
for a raw pointer, but no one would think they need to delete).And of course, the implementation code for smart pointers and iterators will continue to need raw pointers.