为什么暂时取右价的地址是非法的? [英] Why is it illegal to take the address of an rvalue temporary?

查看:165
本文介绍了为什么暂时取右价的地址是非法的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据如何解决警告 rvalue used as lvalue?,Visual Studio将仅对如下代码发出警告:

According to " How to get around the warning "rvalue used as lvalue"? ", Visual Studio will merely warn on code such as this:

int bar() {
   return 3;
}

void foo(int* ptr) {

}

int main() {
   foo(&bar());
}

在C ++中,不允许一个临时的(或者,至少,一个对象由一个右值表达式?)的地址,我认为这是因为临时不能保证甚至有存储。

In C++ it is not allowed to take the address of a temporary (or, at least, of an object referred to by an rvalue expression?), and I thought that this was because temporaries are not guaranteed to even have storage.

但是,尽管诊断可能以编译器选择的任何形式出现,但我仍然希望MSVS出现错误,而不是警告在这种情况下。

But then, although diagnostics may be presented in any form the compiler chooses, I'd still have expected MSVS to error rather than warn in such a case.

那么,临时保证有存储?

So, are temporaries guaranteed to have storage? And if so, why is the above code disallowed in the first place?

推荐答案

你说的是暂时的不能保证甚至具有存储,在临时可以不存储在可寻址存储器中的意义上。实际上,为RISC架构(例如ARM)编译的函数通常会返回通用寄存器中的值,并期望这些寄存器中的输入。

You're right in saying that "temporaries are not guaranteed to even have storage", in the sense that the temporary may not be stored in addressable memory. In fact, very often functions compiled for RISC architectures (e.g. ARM) will return values in general use registers and would expect inputs in those registers as well.

MSVS,对于x86架构,可以始终产生在堆栈上返回其值的函数。因此,它们存储在可寻址的内存中,并具有有效的地址。

MSVS, producing code for x86 architectures, may always produce functions that return their values on the stack. Therefore they're stored in addressable memory and have a valid address.

这篇关于为什么暂时取右价的地址是非法的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆