Could you take a look at these 2 examples and explain me why first attemp of print result gave me wrong number?
First example (printRes pass x by pointer):
int& getInt(int x){
x++;
cout << "int " << x << endl;
return x;
}
void printRes(int *x){
cout << "res " << *x << endl;
}
int main()
{
int t = getInt(5);
printRes(&getInt(5)); // first attemp
printRes(&t); // second attemp
return 0;
}
Second example (printRes pass x by reference):
int& getInt(int x){
x++;
cout << "int " << x << endl;
return x;
}
void printRes(int &x){
cout << "res " << x << endl;
}
int main()
{
int t = getInt(5);
printRes(getInt(5)); // first attemp
printRes(t); // second attemp
return 0;
}
Results:
int 6
int 6
res 2686640
res 6
When I pass 'x' by value it works ok but my target is to get something like this:
- function getInt creates object, puts it in vector (so I just call v.emplace_back()) and returns reference to currently added object (v.back())
- value returned by getInt is passed to printRes which fills object with values from file
I don't want create temporal variables such 't' but pass vector element directly to printRes function but in my more expanded case I have crashes in destructors (or sometimes in some random places).