Scoped pointers versus conventional pointers


Is there any reason to ever use a conventional pointer over a scoped one? I have a project that has a GUI editor of sorts. It uses Haydxn’s layout editor class* which I know works fine. If I use a scoped pointer for this class, as well as my main panel class, I get an access violation the second time the destructor for my plugin editor is called and VS takes me to the following in juce_amalgameted.h:

/** Destructor. This will delete the object that this ScopedPointer currently refers to. */ inline ~ScopedPointer() { delete object; }

If I use conventional pointers and call delete in the destructor everything works fine. I know it’s a bit of a newbie question but can anyone explain to me why this might be happening? I’ve been very careful to use scoped pointers everywhere in my code, and I can’t see why they cause problems in this instance.



Well yes - you should use a conventional pointer if you don’t want your object to be deleted when it goes out of scope!

You problem just sounds like an object is being deleted twice - maybe you create two ScopedPointers to the same object? Stick some breakpoints in your destructors and you should be able to catch it.


Thanks Jules. I can’t think of any reasons for not wanting my objects to get deleted when they go out of scope? Anyway, I’ll persevere with the scoped pointers approach and see if I can locate the problem.


The second time the destructor is called? Just put a breakpoint into your destructor and see what is destroying it the first time :slight_smile:


Found the problem. I think it’s ok now. I was just confused as to why it would work with regular pointers and not scoped ones. I think I’m over the worst now!


The reason to use a conventional pointer is exactly when you don’t own the item. For example, many of my top level items have a pointer to my class Instance but Instance is the last thing to be deleted so none of the references are scoped pointers?

I think the question is more - should you ever call delete? And the answer is basically no. Always used scoped pointers or ref counted pointers or shared pointers…