std::vector::erase weirdness

Started by
4 comments, last by blaze02 18 years ago
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;
    cout << "Adding..." << endl;
    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?
Advertisement
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.
-------Harmotion - Free 1v1 top-down shooter!Double Jump StudiosBlog
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
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 <
Sorry for the above post, but I hope you get the idea.
Quote:Original post by Anonymous Poster
You need to define the = operator


Aaahhh... thats why I don't like C++.
-------Harmotion - Free 1v1 top-down shooter!Double Jump StudiosBlog

This topic is closed to new replies.

Advertisement