Search code examples
c++11shared-ptr

Whether map’s iterator could add shared_ptr's counts?


For example:

#include <memory>

shared_ptr<map<int, int>> ptr1 = make_shared<map<int, int>>();
map<int, int>::const_iterator iter = ptr1->begin();
shared_ptr<map<int, int>> ptr2 = make_shared<map<int, int>>();
ptr1 = ptr2;

My question: Could the iter add the counts of ptr1? In this case, will the ptr1's memory address free after ptr1 = ptr2?


Solution

  • No, it cannot.

    When ptr1=ptr2 runs, the last shared pointer to the first map is gone and the object is destroyed.

    iter is now invalid, and almost any use besides destruction or assigning over it results in undefined behavior.

    Creating an iterator that makes its container persist is possible, if quite intrusive. As a general rule, you should instead learn to keep object lifetime simple and work with object lifetime, not expect smart pointers to solve it for you.