Link to home
Start Free TrialLog in
Avatar of SirSmokeALot
SirSmokeALot

asked on

auto_ptr problem :(

Hi out there,
I've got a memory leak here and can't stuff it :(

Here's the stripped down code:

typedef std::vector<std::auto_ptr<LicenseInfo> > t_LIVector;

t_LIVector FillVector()
{
t_LIVector v;
auto_ptr<LicenseInfo> LI(new LicenseInfo);
v.push_back(LI);
return v;
}

t_LIVector vLI = FillVector();

The memory allocated for LI is never freed why?
I thoughed the auto_ptr class manages all the clean up.

Tobias
ASKER CERTIFIED SOLUTION
Avatar of KangaRoo
KangaRoo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nietod
nietod

>> The issue of auto_ptr's behaviour seems to
>> have plagued the standards committee for a
>> long time. I'm not sure what the final
>> outcome is.
This weird--I would say nearly useles--form was the final decission.  I can't understand why it would have been hotly debated.  There is really only one clear choice, and it isn't this one.  :-)

But, as kangaroo said, you can write a reference counting autopointer class that will work with any STL container.

Typically the reason one doesn't use reference counting is that the object the pointer points to must store a reference count which means that it has to be a struct/class and it has to have some well-defined properties, which means you cannot use the reference counting pointer with the basic types (char, int...) or with class types that were written without these properties (like from a commercial library).  However, it can be done.  You simply store the reference count in a 2nd dynmically allocated memory location.  So the smart pointer class must maintian two pointer data members.  a pointer to the reference count and a pointer to the object that the smart pointer acts like a pointer to.  
Can be implemented different. One class of owning objects keeps the counter and the link to the managed object. The visible smart pointer objects stores only one pointer to a shared owner object. The implementation nietod gives uses one less indirection, so it is a very tiny bit faster, but uses more memory; two pointers in each smart pointer object. But that is all rather insignificant.

Actually the method you suggest is more like what I use.  I was just trying to keep it simple.