std::vector::erase weirdness

Recommended Posts

I just discovered a weird behaviour of std::vector::erase. I've made a program that shows what's happening:
#include <iostream>
#include <vector>

using namespace std;

// a simple class that refcounts an integer
class smartptr
{
public:
smartptr(int nr)
{
m_ptr = new int[2];
m_ptr[0] = 1;
m_ptr[1] = nr;
cout << "Created " << nr << endl;
}
smartptr(const smartptr& rhs) : m_ptr(rhs.m_ptr)
{
if(m_ptr)
++m_ptr[0];
}
~smartptr()
{
if(m_ptr && !--m_ptr[0])
{
cout << "Deleting " << m_ptr[1] << endl;
delete[] m_ptr;
}
}
private:
int* m_ptr;
};

int main()
{
vector<smartptr> testVector;
for(int i = 0; i < 24; ++i)
testVector.push_back(smartptr(i));
cout << "Removing testVector[12]..." << endl;
testVector.erase(testVector.begin() + 12);
cout << "Clearing" << endl;
testVector.clear();
cout << "Done" << endl;

return 0;
}


Basically, I add a bunch of items to a vector and then remove one from about the middle. The object in the middle's deconstructor is not called, but it is removed from the vector. The destructor for the last object in the vector does get called, and it remains in the vector. I've tested this and I get the same thing in both VC6 SP6 and VC8. What's going on?

Share on other sites
Wow, I've never used smart pointers before and now I know why. I suggest anybody that is using them to stop (unless you don't understand exactly what a pointer is).

I stepped through your code in an attempt to help you, but it was utterly confusing. You smartptr copy ctor is getting called something like 5 times every time you vector.push_back(...). Furthermore, you dtor is getting called the same way. The calls are inconsistent (the calls seem to be related to your loop variable i, plus 2; don't ask me why).

I wish I could be of more he -- wait, the first paragraph is great help :)

Put break points in your constructors and destructors and check the variables at each break.

Share on other sites
You need to define the = operator:

...
void operator =(const smartptr& rhs)
{
if(rhs.m_ptr)
++rhs.m_ptr[0];
if(m_ptr && !--m_ptr[0])
{
cout

Share on other sites
You need to define the = operator:

...
void operator =(const smartptr& rhs)
{
if(rhs.m_ptr)
++rhs.m_ptr[0];
if(m_ptr && !--m_ptr[0])
{
cout <

Share on other sites
Sorry for the above post, but I hope you get the idea.

Share on other sites
Quote:
 Original post by Anonymous PosterYou need to define the = operator

Aaahhh... thats why I don't like C++.

Create an account

Register a new account

• Partner Spotlight

• Forum Statistics

• Total Topics
627665
• Total Posts
2978531

• 10
• 10
• 12
• 22
• 13