I've been having problems with a segmentation fault that is driving me crazy. Basically I have a class Expression that contains an Expression_Tree. I'm trying to set my variable current_expression equal to a new expression object from an infix string.
Try to set variable to an expression:
try{
current_expression_ = make_expression(infix); //Segmentation fault here.
}catch(Expression_Error ee){
cerr << ee.what() << endl;
}
make_expression takes an infix string, generates a postfix, then generates a Expression_Tree, creates an Expression object with the expression tree and returns it.
Expression make_expression(const string& infix)
{
string postfix = make_postfix(infix);
cout << "Made postfix" << endl;
Expression_Tree* et= make_expression_tree(postfix);
cout << "Made Expression_Tree" << endl;
cout << "Returning Expression" << endl;
return Expression{et};
}
}
My copy assign operator and swap functions looks like this:
Expression Expression::operator=(const Expression& e) &{
cout << "In copy assign operator" << endl;
Expression{e}.swap(*this);
cout << "Swapped Expression and this" << endl;
return *this;
}
void Expression::swap(Expression& rhs){
cout << "In swap function" << endl;
std::swap(tree, rhs.tree);
}
And my Expression destructor looks like this:
Expression::~Expression(){
cout << "In Expression destructor" << endl;
delete tree;
}
Copy constructor
Expression::Expression(Expression_Tree* input_tree)
:tree(input_tree){}
Output when running the program:
>> u
x=1+1
Made postfix
Made Expression_Tree
Returning Expression
In copy assign operator
In swap function
In Expression destructor
Swapped Expression and this
In Expression destructor
In Expression destructor
Segmentation fault
It seems like the tree is trying to be destroyed two times, so when the destructor gets called the second time it's allready deleated and gives an segmentation fault. Any help in pointing out the problem or any advice is appriciated!