So, I’ve been writing a lot about C++ and pointers. My initial reaction to the things I’ve been reading and learning online has been that they are very bad and should be avoided wherever possible. I’m starting to think this isn’t the right reaction. That’s like saying that we should only use dull knives because sharp knives can cut people. Java is like, here is your dinner sir, we have already pre-cut your steak. With great power comes great responsibility (and juicier steak).
It used to be, I am a C++ programmer, I can handle any new/delete, I know what’s going on, I’ve got this, don’t worry about my code, .. then later.. oh.. oops I guess I forgot to delete that..
oh, I thought you were supposed to delete that? Whose turn is it to take out the garbage?
So I learned a few more things about shared_ptr. I made the mistake of thinking shared_ptr was the solution for everything and that I shouldn’t use raw pointers anymore either.
Two things.
1. There is another std pointer called std::weak_ptr, this is for when you want to use the pointer, but you don’t need to keep a reference count to it. The advantage of this over using a raw pointer is that since a weak_ptr always originates from a shared_ptr, the weak_ptr can at any time be converted to a shared pointer by using the lock() function.
2. Raw pointers are okay, when you ABSOLUTELY KNOW the scope of the object using the pointer is within the scope of the object the pointer points to.
Remember, that the raw pointer should NEVER OWN the object it points to.
Image may be NSFW.
Clik here to view.

Clik here to view.
