开发者

Accelerated C++: Can I substitute raw pointers for smart pointers?

I love this book, sadly it does not cover smart pointers as they were not part 开发者_Go百科of the standard back then. So when reading the book can I fairly substitute every mentioned pointer by a smart pointer, respectively reference?


"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!


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:

template <typename T>
class scoped_ptr
{
 public:
    scoped_ptr(T* p = 0) : mPtr(p) {}
    ~scoped_ptr() { delete mPtr; }
 //...
};

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜