在堆栈上创建的对象的地址是临时的

How are addresses of objects created on the stack temporary

本文关键字:地址 对象 创建 堆栈      更新时间:2023-10-16

我遇到了这个问题,我想知道为什么在方法的堆栈上创建的非常量字符串的地址在请求其地址时返回一个常量指针。我复制粘贴了这里使用的代码示例

void myfunc(string*& val)
{
    // Do stuff to the string pointer
}
int main()
{
    // ...
    string s;
    myfunc(&s);
    // ...
} 

我的问题是,&返回一个变量的地址。在上面的例子中,std::string s是一个non constant,那么为什么它返回的地址是一个常量呢?我想知道的是为什么非常量字符串的地址作为常量地址返回。在堆栈上创建的所有对象的地址都是常量吗?

假设你做了:

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