Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible mem leak?

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;
    }
like image 428
AlexandruC Avatar asked Nov 28 '22 08:11

AlexandruC


1 Answers

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 a shared_ptr to a SString) anywhere, it's dangling... since you don't store the result, you also can not call delete for it - therefore it's destructor won't be called, and in turn also the SString destructor of the contained object won't be called!

If you try

smart_ptr<SString> *p = new smart_ptr<SString>(new SString("but lost")); 
delete p;

instead, you will see the destructor called also for this case.

However, that's no sensible use of a smart_ptr. smart_ptr were created so that you don't need to call delete manually; therefore, don't use them that way; use them as in your first statement!

like image 84
codeling Avatar answered Dec 05 '22 06:12

codeling