I’m new to the concept so don’t be hard on me.
why doesn’t this code produce a destructor call ?
The names of the classes are self-explanatory.
The SString will print a message in ~SString().
It only prints one destructor message.
int main(int argc, TCHAR* argv[])
{
smart_ptr<SString> smt(new SString("not lost"));
new smart_ptr<SString>(new SString("but lost"));
return 0;
}
Is this a memory leak?
The impl. for smart_ptr is from here
edited:
//copy ctor
smart_ptr(const smart_ptr<T>& ptrCopy)
{
m_AutoPtr = new T(ptrCopy.get());
}
//overloading = operator
smart_ptr<T>& operator=(smart_ptr<T>& ptrCopy)
{
if(m_AutoPtr)
delete m_AutoPtr;
m_AutoPtr = new T(*ptrCopy.get());
return *this;
}
By
new smart_ptr<SString>(new SString("but lost"));you are creating a new, dynamically allocated smart pointer. You don’t store the result of the allocation (a pointer to ashared_ptrto aSString) anywhere, it’s dangling… since you don’t store the result, you also can not calldeletefor it – therefore it’s destructor won’t be called, and in turn also theSStringdestructor of the contained object won’t be called!If you try
instead, you will see the destructor called also for this case.
However, that’s no sensible use of a
smart_ptr.smart_ptrwere created so that you don’t need to calldeletemanually; therefore, don’t use them that way; use them as in your first statement!