Reputation: 4634
If you would like to see the code that causes this issue you can view and clone the project here: https://github.com/NickChapman/RuM/tree/63047e457745558403ea807534e4f5b9930cfeb8
The noteworthy bit is that inside a constructor I have (RuMParser.cpp
line 20):
this->globalScope = Scope();
std::cout << &(this->globalScope) << std::endl;
and then immediately after the constructor finishes I have (RuM.cpp
line 63):
std::cout << &(this->parser.globalScope) << std::endl;
The output from these is:
0x7fff57ac5318
0x7fff57ac6988
Why are they not the same? For all of the rest of time the address will remain fixed at the second value. Why does it change after leaving the constructor?
I noticed this issue when trying to establish a pointer immediately after the first print out. The pointer is to an older address the second the constructor finishes and I am baffled as to why.
My suspicion is that this has something to do with copy constructors or something of that nature.
Edit: For reference if you are trying to build the source and run you can just:
cmake .
make
then
./rum
Entering x=1;$
will cause the program to segfault.
Upvotes: 0
Views: 1144
Reputation: 6901
this->parser = RuMParser(tokenList);
std::cout << &(this->parser.globalScope) << std::endl;
First, a temporary RuMParser
is created and this is when you get the first print. The temporary is then copy constructed into this->parser
. That means, globalScope
is default constructed again. Thus the different address in the later print.
Well, there are quite a few questionable/non-idiomatic things in the code, but I will stick to only what matters to this question. You can rewrite the constructor as:
RuMInterpreter::RuMInterpreter():
tokenList(std::make_shared<std::vector<Token>>())
,parser(tokenList)
{
....
}
Always prefer member initializer list whenever possible. It is also one of the items in effective C++ book I guess.
Upvotes: 2