deque::clear Causing CRT Error

I currently have a destructor method (not ~classname) for a base class which is to be used by derived classes within their own destructor. During the execution of the base class's destructor, I remove a corresponding section in a deque using an iterator. Unfortunately, this causes a CRT error which I don't understand. Here's the code I'm using for my destructor:

1
2
3
void cbDestruct ( ) {
	rectStack.erase ( _rectPos );
}


It's not the whole thing, but you really only need to see the call to erase(). There's nothing before that call anyways.

The iterator _rectPos is defined as:
std::deque<hgeRect*>::iterator _rectPos;

And is set in the constructor:

1
2
3
4
5
6
7
8
9
void cbConstruct ( ) {
	rectStack.push_back ( &collisionRect );
	_rectPos = rectStack.begin ( );
	for ( int i = 0; i < rectStack.size()-1; i++ ) {
		_rectPos++;
	}

	// set some variables
}

I know I'm probably doing it wrong, but there is no overloaded operator for real values. Only for other iterators.

Here's how the function is being called:
1
2
3
4
Player::~Player(void)
{
	cbDestruct ( );
}

I know, it's a huge destructor, but try to live through it. I put both the deque and the player object in the global scope and set them as static.


So, the question is, obviously, what's causing the problem? Is the iterator out of bounds? Is the deque being destroyed before the destructor is called? I'm fairly new to iterators, so I'm not entirely sure.
Last edited on
deque iterators go bad as soon as you add or remove an item from the deque. Therefore every time you add a new object to this rectStack deque, all of your _rectPos iterators are borking.

If you want your iterators to stay good, you can use a different container, like a list. list iterators stay good no matter how many other elements you add/remove.

Also you don't need to do this:

1
2
3
4
	_rectPos = rectStack.begin ( );
	for ( int i = 0; i < rectStack.size()-1; i++ ) {
		_rectPos++;
	}


You can just do: _rectPos = rectStack.end()-1;


If rectStack is global, you'll also run into initialization/destruction order problems if any of these objects are global (typically you want to avoid gobals for this reason -- among others).
Thanks, I knew there must've been an easier way to initialize the iterator.

But what exactly is the order in which objects are constructed? Does it depend on which compiler is used?

EDIT: I see what you mean. I'll just stick with declaring pointers in the global namespace and creating them dynamically. Thanks.
Last edited on
Topic archived. No new replies allowed.