In the following code I am trying to create Widget objects using a WidgetMaker class which is a friend of Widget and is thus able to call its private constructor. Can anyone tell me why the auto_ptr destructs after calling Widget::asString() in the following code? How should I have done this?
It doesn't get destroyed in asString, it is destroyed in getWidget.
At the end of the function pWidget goes out of scope and is destroyed, which also destroys the Widget.
Thanks for your replies. It was a very simple error that I made. In fact it was only after stripping down my original code and rewriting it in terms of Widgets etc for this post that I finally realised it was to do with auto_ptr. My original "Widget" class contained a lot of other members which were mainly inbuilt types (and thus did not get destructed). This meant that the errors I was getting didn't arise until much later when the memory started getting overwritten. NASTY!
Actually I don't want to release the pointer. Otherwise there is no point in using a smart pointer in the first place since the caller would have to remember to delete it. Instead I think I really need to return the object as an auto_ptr. Here is what I hope is the correct code: