C++: Why is the destructor being called here?
I guess I don't fully understand how destructors work in C++. Here is the sample program I wrote to recreate the issue:

    #include <iostream>
    #include <memory>
    #include <vector>
    
    using namespace std;
    
    struct Odp
    {
    	int id;
    
    	Odp(int id)
    	{
    		this->id = id;
    	}
    
    	~Odp()
    	{
    		cout << "Destructing Odp " << id << endl;
    	}
    };
    
    typedef vector<shared_ptr<Odp>> OdpVec;
    
    bool findOdpWithID(int id, shared_ptr<Odp> shpoutOdp, OdpVec& vec)
    {
    	shpoutOdp.reset();
    
    	for (OdpVec::iterator iter = vec.begin(); iter < vec.end(); iter++)
    	{
    		Odp& odp = *(iter->get());
    		if (odp.id == id)
    		{
    			shpoutOdp.reset(iter->get());
    			return true;
    		}
    	}
    
    	return false;
    }
    
    int main()
    {
    	OdpVec vec;
    
    	vec.push_back(shared_ptr<Odp>(new Odp(0)));
    	vec.push_back(shared_ptr<Odp>(new Odp(1)));
    	vec.push_back(shared_ptr<Odp>(new Odp(2)));
    
    	shared_ptr<Odp> shOdp;
    	bool found = findOdpWithID(0, shOdp, vec);
    	found = findOdpWithID(1, shOdp, vec);
    }

The output of this program is:


    Destructing Odp 0
    Destructing Odp 1

Why does this happen? I'm retaining a reference to each of the `Odp` instances within the vector. Does it have something to do with passing a `shared_ptr` by reference?

C++: Why is the destructor being called here?
===

I guess I don't fully understand how destructors work in C++. Here is the sample program I wrote to recreate the issue:

    #include <iostream>
    #include <memory>
    #include <vector>
    
    using namespace std;
    
    struct Odp
    {
    	int id;
    
    	Odp(int id)
    	{
    		this->id = id;
    	}
    
    	~Odp()
    	{
    		cout << "Destructing Odp " << id << endl;
    	}
    };
    
    typedef vector<shared_ptr<Odp>> OdpVec;
    
    bool findOdpWithID(int id, shared_ptr<Odp> shpoutOdp, OdpVec& vec)
    {
    	shpoutOdp.reset();
    
    	for (OdpVec::iterator iter = vec.begin(); iter < vec.end(); iter++)
    	{
    		Odp& odp = *(iter->get());
    		if (odp.id == id)
    		{
    			shpoutOdp.reset(iter->get());
    			return true;
    		}
    	}
    
    	return false;
    }
    
    int main()
    {
    	OdpVec vec;
    
    	vec.push_back(shared_ptr<Odp>(new Odp(0)));
    	vec.push_back(shared_ptr<Odp>(new Odp(1)));
    	vec.push_back(shared_ptr<Odp>(new Odp(2)));
    
    	shared_ptr<Odp> shOdp;
    	bool found = findOdpWithID(0, shOdp, vec);
    	found = findOdpWithID(1, shOdp, vec);
    }

The output of this program is:


    Destructing Odp 0
    Destructing Odp 1

Why does this happen? I'm retaining a reference to each of the `Odp` instances within the vector. Does it have something to do with passing a `shared_ptr` by reference?
