C ++临时和构造函数 [英] C++ temporaries and constructors

查看:119
本文介绍了C ++临时和构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么有些编译器抱怨从构造函数中获取临时地址,有些不是?



例如:

  WriteLine(& String8(Exception)); 

我假设抱怨的编译器不会将该地址存储在堆栈上,我忽略了警告。有办法让它在一行上工作吗?是最好的/唯一的方式一个静态方法的类返回一个地址?我不认为一个静态方法的String8类返回一个指针将工作,因为它会将String8类保存到寄存器,然后在WriteLine()中吃它

解决方案

您提供的示例代码

  WriteLine(& String8 )); 

作为标准C ++ 无效,除非 String8 type定义自定义地址运算符。







$ b


为什么有些编译器抱怨从构造函数中获取临时地址,有些不是?




有些编译器抱怨,因为C ++标准说你不能使用内置的地址运算符来取一个临时的地址:


C ++ 11§5.3.1/ 3

“一元的结果 & 运算符是指向其操作数的指针。


有些编译器,例如Visual C ++,不要抱怨,因为他们提供以语言扩展作为地址的能力。






请注意,用户定义的类型可以定义自定义地址运算符。因此,在您的情况下,它取决于 String8 类型。以及编译器。



b blockquote>

有办法让它在一行中工作吗?


您可以定义地址运算符。但这不是一个好主意。首先,它只会造成标准库等的问题,其次,这是非常少见的需要。



我只能记得一个案件,我认真考虑过一个解决方案,即用于传递COM智能指针作为输出参数。而不是定义一个地址操作符我定义了一个命名的方法。它更清楚,不会干扰其他事情。


Why do some compilers complain about taking an address of a temporary from a constructor and some dont?

For example:

WriteLine(&String8("Exception"));

I'm assuming the complaining compiler is not storing that address on the stack and it will blow up if I ignore the warning. Is there a way to get that to work in one line? Is the best/only way a static method on the class that returns an address? Hmm I don't think a static method on the String8 class that returns a pointer would work since it would save the String8 class to a register and then eat it in WriteLine()

解决方案

The example code you give,

WriteLine(&String8("Exception"));

is invalid as standard C++, unless the String8 type defines a custom address operator.


You ask,

“Why do some compilers complain about taking an address of a temporary from a constructor and some dont?”

Some compilers complain, because the C++ standard says you can't use the built-in address operator to take the address of a temporary:

C++11 §5.3.1/3:
“The result of the unary & operator is a pointer to its operand. The operand shall be an lvalue or a qualified-id.”

Some compilers, such as Visual C++, don't complain, because they offer the ability to take the address as a language extension.


Note that a user defined type can define a custom address operator. Thus, in your case it depends on the String8 type. As well as on the compiler.


You further ask,

“Is there a way to get that to work in one line?”

Yes you can define an address operator. But it's not a good idea. First of all it only creates problems with standard library etc., and secondly, the need for that is very rare.

I can only remember one case where I seriously considered such a solution, namely for passing a COM smart pointer as out-argument. Instead of defining an address operator I defined a named method. It's much more clear and doesn't interfere with other things.

这篇关于C ++临时和构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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