简体   繁体   中英

Memory leak when create std::shared_ptr to assign member variable

Here is a one example class.

class Test {
private:
    std::shared_ptr<int> m_iTest;
    void testLoop(void);
};


void Test::testLoop(void)
{
    for (int i = 0; i < 5; i++)
       m_iTest = std::make_shared<int>;
}

In this code, when called testLoop function, allocate new int type memory and assigned to m_iTest member variable. The first loop (i=0), create new memory and assigned to m_iTest. And the second loop (i=1), create new memory and assigend to m_iTest.........Hm??? What about the first created memory? Is it deleted or not? And the third loop (i=2), create new memory and assigned to m_iTest....Hm..???

So, I think this code occurs memory leak, right? Or shared_ptr can be deleted automatically?

(It's just sample code. not about use vector or any...)

When you assign to a std::shared_ptr , the reference count for the previously managed object (if there was one) goes down by 1. So in your loop, when you call make_shared the first time, you create a new object with a reference count of 1. When you call it the second time, you create another object with a reference count of 1, and the reference count for the previous object goes down to 0, causing it to be deleted.

So no, there is no memory leak. If there was, it would be a poorly designed "smart" pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM