简体   繁体   中英

C++ function when is the return value deleted?

I have the following code in c++.

string getName()
{
    return "C++";
}

void printName(const char* name)
{
    cout << name << endl;
}

int main()
{
    printName(getName().c_str());
}

The function getName returns a string . I am passing the c_str pointer of the string to printName function. I want to know will the returned string deleted before the printName() function is called. If not then when is the returned value deleted.

The temporary will be destroyed after the full expression.

All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation.

The temporary created by getName() will be destroyed after the full expression which includes the execution of printName() , the pointer got from c_str remains valid inside printName() .

In the given example sequence of execution would be like this

  1. getName() will get executed it will return string.

  2. Reference of above return string will be used by c_str() function.

  3. finally printName will get executed, then return object will get destroyed, return value will not be destroyed before printName execution of this function.

As full expression will get executed in lexical order and temporary created objects will get destroyed after the scope ends.

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