取临时对象的地址 [英] taking the address of a temporary object
问题描述
§5.3.1一元运算符,第3节
§5.3.1 Unary operators, Section 3
operator是指向其操作数的指针。 操作数应为小值或限定ID。
应为在这种情况下?这是否意味着采取临时地址的地址是错误的?我只是想知道,因为g ++只给我一个警告,而gotau拒绝编译以下程序:
What exactly does "shall be" mean in this context? Does it mean it's an error to take the address of a temporary? I was just wondering, because g++ only gives me a warning, whereas comeau refuses to compile the following program:
#include <string>
int main()
{
&std::string("test");
}
g ++ 警告:采取临时
comeau 错误地址:表达式必须是左值或函数指示符
comeau error: expression must be an lvalue or a function designator
有人有Microsoft编译器或其他编译器,可以测试这个程序吗?提前感谢。
Does anyone have a Microsoft compiler or other compilers and can test this program, please? Thanks in advance.
推荐答案
标准语言中的shall一词意为严格的要求。所以,是的,你的代码是错误的(它是一个错误),因为它试图将运算符应用到非值的对象。
The word "shall" in the standard language means a strict requirement. So, yes, your code is ill-formed (it is an error) because it attempts to apply address-of operator to a non-lvalue object.
但是,这里的问题不是尝试采取临时的地址。问题是,再次采取非空值的地址。临时对象可以是左值或非右值,这取决于生成该临时值的表达式或提供对该临时值的访问。在你的情况下,你有 std :: string(test)
- 一个函数式样转换为非引用类型,根据定义产生非左值。因此错误。
However, the problem here is not an attempt of taking address of a temporary. The problem is, again, taking address of a non-lvalue. Temporary object can be lvalue or non-lvalue depending on the expression that produces that temporary or provides access to that temporary. In your case you have std::string("test")
- a functional style cast to a non-reference type, which by definition produces a non-lvalue. Hence the error.
如果你想取一个临时对象的地址,你可以这样做,例如
If you wished to take address of a temporary object, you could have worked around the restriction by doing this, for example
const std::string &r = std::string("test");
&r; // this expression produces address of a temporary
,只要临时存在,结果指针保持有效。还有其他方法合法获取临时对象的地址。这只是你的具体方法恰巧是非法的。
whith the resultant pointer remaining valid as long as the temporary exists. There are other ways to legally obtain address of a temporary object. It is just that your specific method happens to be illegal.
这篇关于取临时对象的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!