I am a new user here and this is my first question, so please don't judge me hard. I cheked many similar questiontions like this not only on this site, also on others too. But I didn't find the answer.
The problem is to create copy constructor with pointers. For those people who may ask: why do you need pointers?: I have a class stmt
, which contains vector<stmt>
, it will allow me to construct tree-like data structure. Then I will perform some functions to change values of stmt's parameters. Without pointers they won't change
It compiles, but then gives Exception Unhandled (Runtime error)
My first attemp looks like this:
struct stmt
{
string lexeme;
int *size;
int *lay;
bool *nl;
vector<stmt>* follow;
stmt(string l)
{
lexeme = l;
size = new int;
*size = l.size()+2;
lay = new int;
*lay = 0;
nl = new bool;
*nl = false;
follow = new vector<stmt>;
}
stmt(const stmt &s)
{
lexeme = s.lexeme;
size = new int; //Crashes here : Unhandled exception:std::length_error at memory location ...
*size = *s.size;
lay = new int;
nl = new bool;
follow = new vector<stmt>;
follow = s.follow;
}
};
Second time I tried also this:
stmt(const stmt &s)
:lexeme.(s.lexeme), size (s.size), ......and so on
{}
Unfortunately, this also doesn't help.
So, this is my third attemp but didn't help
IMPORTANT: I noticed that it happens when I am trying to create and emplace_back
new stmt
element in a vector of another stmt
using functions which return type is stmt
.
Here is a code which represents the key problem:
stmt Program("Program");
stmt ParseRelop(string p);
void EMP(stmt s)
{
s.follow->push_back(ParseRelop("token"));
}
stmt ParseRelop(string p)
{
stmt s(p);
return s;
}
int main()
{
EMP(Program);
cout<<Program.follow->at(0).lexeme;
}