Hello I have a class with a function that returns a pointer:
int* Maze::GetStart()
{
int startNode = 1;
return &startNode;
}
Will the value of startNode be erased after the function returns the pointer?
If I did this instead would the value be saved?
int Maze::GetStart()
{
int startNode = 1;
return startNode ;
}
main
{
int* pStart = maze.GetStart();
}
The variable
startNodewill cease to exist once the functionGetStart()returns, so in that sense, yes.But, your code opens up a huge opportunity for undefined behavior by returning addresses to things that will disappear once
GetStart()returns. If the caller attempts to dereference the returnednode*, anything can happen. Also, the code can’t possibly compile as-is since you can’t implicitly cast anint*to anode*.However, if you’re returning by value, then you should be fine: