我在linux g++3.2.2下运行,底层容器不同结果也不同,以deque和vector为底层容器时,栈空时top调用导致段错误。以list为底层容器时top调用返回0。

栈top()会调用底层容器的back()操作,deque和vector为空时,back()操作会使用空指针,而list为双向循环链,有一个作为链头的标志块,所以调用back()是不会导致空指针操作。但执行pop()操作时会出错。

#include <stack>

#include <list>

#include <iostream>

using namespace std;


int main() {

 stack< int, list<int> > s;

 cout << "s.top()=" << s.top() << endl;

 s.pop();

}


STL对空栈调用top和pop应该是未定义的,可能设计者认为使用STL的人应该知道自己在做什么,如果想要比较安全的使用,可能JAVA的异常机制会更理想一些。