在堆栈上创建的对象的地址是临时的
How are addresses of objects created on the stack temporary
我遇到了这个问题,我想知道为什么在方法的堆栈上创建的非常量字符串的地址在请求其地址时返回一个常量指针。我复制粘贴了这里使用的代码示例
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);
}
相关文章:
- 空基优化子对象的地址
- 被解释为低级别const的const对象的地址
- 将地址分配给本地指针后,公共对象的变量将消失
- 如何在C++中获取该对象的类声明中对象的地址?
- 当一个新对象被分配到它的地址时,对象是否必须被销毁
- 已转换对象的地址
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- 如何从绝对地址的 C 样式指针创建对C++对象的引用
- 是否通过向封闭对象的地址添加字节偏移量来访问子对象
- C++ - 非静态 void* 成员,指向具有相同地址但不同值的不同对象的另一个非静态成员
- 为什么按值返回的对象与方法中的对象具有相同的地址?
- 这个指针指向给定的对象还是给定对象的地址
- 对象地址是否保证是其类型对齐的倍数
- C++多态性:有没有办法找到对象成员函数的地址?
- 如何在 c++ 中操作当前对象的地址?
- static_casting基对象的地址到派生类的指针
- 如果我有指向基类对象的指针,如何获取虚拟方法的地址?
- 更改保留指向其字段的原始指针的对象地址
- 在 std::map 中插入对象时构造函数中变量的地址
- C++:获取包含成员子对象的完整对象的地址