BrokenClockwork
BrokenClockwork

Reputation: 101

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 of the standard back then. So when reading the book can I fairly substitute every mentioned pointer by a smart pointer, respectively reference?

Upvotes: 4

Views: 902

Answers (3)

Terrance Cohen
Terrance Cohen

Reputation: 81

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

Upvotes: 4

Ben Voigt
Ben Voigt

Reputation: 283971

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.

Upvotes: 2

vdsf
vdsf

Reputation: 1618

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.

Upvotes: 2

Related Questions