简体   繁体   中英

How are addresses of objects created on the stack temporary

I came across this question and I would like to know why the address of a non constant string created on the stack of a method returns a constant pointer when its address is requested. I have copy-pasted the code sample used there

void myfunc(string*& val)
{
    // Do stuff to the string pointer
}

int main()
{
    // ...
    string s;
    myfunc(&s);
    // ...
} 

My question is that & returns the address of a variable. So In the above case the std::string s is a non constant then why is it returning its address as a constant ? What I want to know is why the address of the non-constant string is returned as a constant address. Are the addresses of all objects created on the stack constant ?

Let's say you did:

void myfunc(string*& val)
{
    val = NULL;
    // How is that supposed to affect the variable s in main?
    // You can't change the address of the object in main.
    // Once a variable is created, its address cannot be modified.
}

int main()
{
    // ...
    string s;

    // Since the address of s cannot be changed,
    // the type of &s is "string* const" not "string&".

    // That's why the call to myfunc is wrong.
    myfunc(&s);
} 

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