Introducing auto-free List<T> in Node.hpp

This commit is contained in:
Stefano Sanfilippo 2014-11-28 19:32:35 +01:00
parent 1cd565a1f0
commit 7050c5586e

View File

@ -40,25 +40,30 @@ public:
}; };
class StatementList: public std::vector<Statement*>, public Emittable { template<class T>
class List: public std::vector<T*> {
public: public:
virtual ~StatementList() { virtual ~List() {
for (Statement *s: *this) { for (T *element: *this) {
delete s; delete element;
} }
} }
};
class StatementList: public List<Statement>, public Emittable {
public:
virtual void emit(std::ostream &stream, int indent = 0); virtual void emit(std::ostream &stream, int indent = 0);
}; };
template <class T> template <class T>
class ListEmittable: public std::vector<T>, public Emittable { class ListEmittable: public List<T>, public Emittable {
public: public:
virtual void emit(std::ostream &stream, int indent = 0) { virtual void emit(std::ostream &stream, int indent = 0) {
if (this->size() > 0) { if (this->size() > 0) {
T last = this->back(); // TODO wut? T *last = this->back(); // TODO wut?
for (T e: *this) { for (T *e: *this) {
e->emit(stream); e->emit(stream);
if (e != last) { if (e != last) {
stream << getSeparator(); stream << getSeparator();
@ -67,12 +72,6 @@ public:
} }
} }
virtual ~ListEmittable() {
for (T e: *this) {
delete e;
}
}
protected: protected:
virtual std::string getSeparator() const { virtual std::string getSeparator() const {
return ", "; return ", ";
@ -80,7 +79,7 @@ protected:
}; };
class ExpressionList: public ListEmittable<Expression*> { class ExpressionList: public ListEmittable<Expression> {
}; };
@ -100,7 +99,7 @@ private:
}; };
class IdList: public ListEmittable<Id*> { class IdList: public ListEmittable<Id> {
}; };
@ -226,6 +225,7 @@ private:
class BranchCase: public Emittable { class BranchCase: public Emittable {
public: public:
BranchCase(SemiExpression *c, StatementList *b): condition(c), body(b) {} BranchCase(SemiExpression *c, StatementList *b): condition(c), body(b) {}
virtual ~BranchCase() {}
virtual void emit(std::ostream &stream, int indent = 0); virtual void emit(std::ostream &stream, int indent = 0);
private: private:
@ -234,7 +234,7 @@ private:
}; };
typedef std::vector<BranchCase*> BranchCaseList; typedef List<BranchCase> BranchCaseList;
class Branch: public Statement { class Branch: public Statement {
@ -276,12 +276,6 @@ private:
class Program: public Emittable { class Program: public Emittable {
public: public:
virtual ~Program() {
for (Function *f: functions) {
delete f;
}
}
virtual void emit(std::ostream &stream, int indent = 0); virtual void emit(std::ostream &stream, int indent = 0);
void setMain(Main *m) { void setMain(Main *m) {
@ -294,7 +288,7 @@ public:
private: private:
std::unique_ptr<Main> main; std::unique_ptr<Main> main;
std::vector<Function*> functions; List<Function> functions;
}; };