mercredi 2 août 2017

Unexpected value returned by use_count() of shared_ptr while retrieving from vector

The program below is outputting unexpected use_count() value when shared pointer is printed using iterator de-reference of std::vector:

#include<iostream>
#include<memory>
#include<vector>

class A;

typedef std::shared_ptr<A>            sharedPtr;
typedef std::vector<sharedPtr>        sharedPtrVect;
typedef sharedPtrVect::const_iterator vectItr;

class A
{
  public:
    A(int inp): m_Val(inp) { /*std::cout << "*** A ctor called: " << m_Val << " ***" <<std::endl;*/ }
    ~A() { /*std::cout << "### A dtor called: " << m_Val << " ###" <<std::endl; */}

    int getVal() const { return m_Val; }

  private:
    int m_Val;
};

int main()
{
  sharedPtrVect myVect1, myVect2;
  vectItr myVectItr;
  std::shared_ptr<A> tmpPtr;

  for(int i = 1 ; i <= 5 ; i++ ) {
    std::cout << "Pushed back: " << i << std::endl;
    tmpPtr = std::make_shared<A>(i);
    myVect1.push_back(tmpPtr);
  }

  myVectItr = myVect1.begin();

  for(  ;  myVectItr != myVect1.end() ; ++myVectItr) {
    std::cout << "-----------------------------" << std::endl;
    std::cout << "Element number: " << (*myVectItr).get()->getVal() << std::endl;
    std::cout << "Element use count: " << (*myVectItr).use_count() << std::endl;
    std::cout << "-----------------------------" << std::endl;
  }

  return 0;
}

The output of the above code is:

Pushed back: 1
Pushed back: 2
Pushed back: 3
Pushed back: 4
Pushed back: 5
-----------------------------
Element number: 1
Element use count: 1
-----------------------------
-----------------------------
Element number: 2
Element use count: 1
-----------------------------
-----------------------------
Element number: 3
Element use count: 1
-----------------------------
-----------------------------
Element number: 4
Element use count: 1
-----------------------------
-----------------------------
Element number: 5
Element use count: 2     //I am not sure why or how this is 2?
-----------------------------

I don't understand how the use_count() for the last vector element is 2. Shouldn't it be 1 like others? I am not creating any copies of the shared pointer stored in the last element of the vector. What am I missing here?

EDIT: I have good experience in C++98, but less experience in C++11.

Aucun commentaire:

Enregistrer un commentaire