简体   繁体   中英

Returning a pointer from a member function in C++

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();
}

Will the value of startNode be erased after the function returns the pointer?

The variable startNode will cease to exist once the function GetStart() 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 returned node* , anything can happen. Also, the code can't possibly compile as-is since you can't implicitly cast an int* to a node* .

However, if you're returning by value, then you should be fine:

int Maze::GetStart() 
{ 
    int startNode = 1; 
    return startNode; 
    // return 1; // Why not do this?
} 

int pStart = maze.GetStart(); // Get returned value as int, not pointer to int. 

Returning address of a variable allocated on stack does not make sense at all. The life time of the variable startNode gets over as soon as the function GetStart() returns. It does not matter if it is a free function or member function.

I think, in gcc/g++ there is a warning for this.

Based on the question edit:

If you want to modify the variable and save the modified state then it must be declared static . See static local variables .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM