原因是T为引用,T为对象时,当跳出作用域,(保存在栈中)析构了。
Stack.h
#ifndef STACK_H
#define STACK_Htemplate<typename T>
class Stack
{
private:
struct Link
{
const T& value;
Link* next;
Link(const T& val,Link* nxt):value(val),next(nxt){}
}*Head;
public:
Stack():Head(NULL){}
virtual ~Stack()
{
while (Head)
{
pop();
}
}
void push(const T& val)
{
Head=new Link(val,Head);
}
const T& top() const
{
assert(Head!=NULL);
return Head->value;
}
void pop()
{
assert(Head!=NULL);
Link* oldHead=Head;
Head=Head->next;
delete oldHead;
}
};
#endif
Test.cpp
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include "Stack.h"
using namespace std;
int main(int argc,char* argv[])
{
Stack<string> textline;
for (int i=0;i<4;i++)
{
const string& s="123";
textline.push(s);
}
for (int i=0;i<4;i++)
{
cout<<textline.top()<<endl;
textline.pop();
}
system("pause");
return 0;
}