Is auto_ptr good to work with only for local variables?
If I need to work with classes too, do i need copied pointer ?
2 Answers
The auto_ptr destructor does deallocate the memory, so you are correct. Once you leave the auto_ptr's scope the thing you're pointing to will go away. You might be looking for something like a shared_ptr, which is a reference counted smart pointer. It will be part of the next C++ standard. Boost has an implementation of it, and it's also part of the TR1 library. If your compiler supports std::tr1 entities then you should have the shared_ptr.
Edit
As pointed out in comments, auto_ptr copy semantics cause a transfer of ownership that does not necessarily result in deletion of the object. So, an auto_ptr type variable can be assigned to another, and could be used as a function return value. The key with auto_ptr is that only one of them at a time can reference a particular entity.
I think I was assigning the traits of scoped_ptr to auto_ptr incorrectly and a little unfairly. My own bias is against auto_ptr because that transfer of ownership causes a side effect on the source object that is not normally associated with copying.
3 Comments
boost::scoped_ptr or std::unique_ptr are the apples-to-apples proper replacements for std::auto_ptr.std::auto_ptr's copy constructor implements ownership transfer semantic, so if you return a local auto_ptr the ownership will be transferred to the returned instance of auto_ptr i.e. to the caller.
std::auto_ptrhas been deprecated in favor ofstd::unique_ptr.