vector::pop_back issue

S

Sarath

Dear All,

at the time class destruction, application error occurs. Seems the
heap was corrupted with the pop_back operation on empty vector.

the code failed to execute in Visual C++ 6 and 2008. but worked fine
in DevCPP. I admit that the pop function should check for empty
vector. but still the different behavior concludes, it's a bug in
Microsoft STL Implementation


template<class T>
class TestStack
{
public:
TestStack<T>() { _stack.reserve(1024); }
~TestStack<T>() { _stack.clear(); }
T pop()
{
T Obj = _stack.back();
_stack.pop_back();
return Obj;
}
void push( const T& element )
{ _stack.push_back( element ); }
bool clear( void ) { _stack.clear(); }
private:
deque<T> _stack;
};

int main( void )
{
TestStack<int> StackObj;
StackObj.pop();
StackObj.push( 10 );
StackObj.push( 20 );
StackObj.push( 30 );
StackObj.push( 40 );
return 0;
}
 
L

Lionel B

Dear All,

at the time class destruction, application error occurs. Seems the heap
was corrupted with the pop_back operation on empty vector.

How surprising.
the code failed to execute in Visual C++ 6 and 2008. but worked fine in
DevCPP. I admit that the pop function should check for empty vector. but
still the different behavior concludes, it's a bug in Microsoft STL
Implementation

Errrm... right... and what do you think *should* happen if you pop an
empty deque?
 
S

Sarath

As far as I know, the result of calling pop_back() on an empty container
is undefined. As such, no implementation could possibly be broken when
you do such a thing because the implementation can do whatever it wants.


Why not use std::stack?


What are you going to do in the above if T's copy constructor throws
when Obj is returned? You don't get the popped object and it is no
longer in the container.

Better would be to maintain command-query separation. Use back() to
access the last element and pop_back when it is no longer needed.

thanks Daniel.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,173
Messages
2,570,938
Members
47,475
Latest member
NovellaSce

Latest Threads

Top