Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 966
BrokenClockwork Avatar asked Feb 25 '23 01:02

BrokenClockwork


2 Answers

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

like image 114
Terrance Cohen Avatar answered Feb 27 '23 13:02

Terrance Cohen


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.

like image 37
vdsf Avatar answered Feb 27 '23 15:02

vdsf