Reputation: 91
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...)
Upvotes: 0
Views: 708
Reputation: 103713
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.
Upvotes: 3