【问题标题】:How are addresses of objects created on the stack temporary在堆栈上创建的对象的地址是如何临时的
【发布时间】:2015-05-26 17:15:04
【问题描述】:

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

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

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

我的问题是& 返回一个变量的地址。那么在上述情况下,std::string snon constant 那么为什么它会将其地址作为常量返回?我想知道的是为什么将非常量字符串的地址作为常量地址返回。堆栈上创建的所有对象的地址都是常量吗?

【问题讨论】:

  • 不知道投反对票的原因。
  • A string const* ponter 仍然可以指向一个非 const 实例,不清楚你在问什么。变量本身是 const 与它的地址的 constness 无关。
  • AFAIK, *& 什么都不做。您正在从其引用中获取指针的值,因此,与仅获取 string 值相同。
  • 也许是因为你的问题是错误的......'不清楚'?
  • 我会在问题中添加更多细节

标签: c++


【解决方案1】:

假设你做到了:

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

【讨论】:

  • 感谢您解决这个问题。所以你是说一个对象在堆栈上创建时实际上有一个常量地址。
  • @Rajeshwar,对象的地址,无论是在堆栈上还是全局的,都是不变的。
  • &sstring * 类型的纯右值并且对string * 类型的左值的引用(你的函数的参数类型)不能绑定到它
猜你喜欢
  • 2016-08-25
  • 1970-01-01
  • 2012-08-12
  • 2016-03-06
  • 2010-09-24
  • 2010-12-08
  • 1970-01-01
  • 2021-01-10
  • 2020-04-09
相关资源
最近更新 更多