Possible leakage of the membrane?

I am new to this concept, so it’s not difficult for me. why does this code not call the destructor? Class names are self-explanatory. SString will print the message in ~ SString (). It prints only 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 it a memory leak? Imp. for smart_ptr is here

edited by:

 //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; } 
+4
source share
4 answers

In new smart_ptr<SString>(new SString("but lost")); you are creating a new dynamically assigned smart pointer. You do not save the distribution result (pointer to shared_ptr to SString ) anywhere, it hangs ... since you do not save the result, you also cannot call delete for it - therefore, the destructor will not be called, and in turn, the SString destructor the contained object will not be called!

If you try

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

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

However, that is a reasonable use of a smart_ptr . smart_ptr were created so that you do not need to call delete manually; therefore do not use them in this way; use them as in your first application!

+8
source

The point of a smart pointer is that you should only have automatic smart pointer objects:

 { smart_ptr<Foo> p(new Foo); } // bye bye Foo 

The second line, however, creates a dynamic smart pointer, whose life never ends! Thus, he will never have the opportunity to destroy the object for which he is responsible.

You will need to manually delete the smart pointer so that it can clean the object:

 auto sp = new smart_ptr<Foo>(new Foo); // ^^^^^^^ // ^^^^^^^^^^^^^^ +------< dynamic Foo, handled by the SP // | // +---------------< dynamic smart pointer, handled by YOU delete sp; 
+8
source

Yes, the intellectual point itself has leaked. (And all that he refers to).

I can't think of a good reason for a new smart pointer ...

+5
source

Yes, this is a memory leak, you are a leak of the second smart pointer and its contents.

The reason is that the first smart pointer is created on the stack, so its lifetime is limited by the block in which it is declared, after which it will be automatically destroyed.

The second one is created on the heap, which means that it will live until you destroy it with delete , at that moment its destructor will be called (and with this it holds the SString destructor).

+3
source

Source: https://habr.com/ru/post/1434217/


All Articles