[英]Using temporary object by non-const reference within a single statement in C++
Here is the code: 这是代码:
namespace NS
{
class B
{
public:
template<typename T> friend B& operator<<(B& b, T const& obj);
};
template<typename T> B& operator<<(B& b, T const& obj)
{
// using b and obj
return b;
}
}
int main()
{
NS::B() << 2.71 << 123 << "abcdef"; // doesn't compile in gcc
NS::B b; b << 2.71 << 123 << "abcdef"; // OK
}
The first line in main compiles in VS2015 (and some earlier ones) and doesn't compile in gcc (I tried in 6.3, 4.3.2). VS2015中main的第一行(以及一些早期版本)在gcc中不编译(我在6.3、4.3.2中尝试过)。
Which compiler does the right thing? 哪个编译器做对了? I thought the temporary object's (NS::B()) lifetime would be up to the end of the statement (;), so it's ok to pass it to my operator<< by non-const reference.
我认为临时对象(NS :: B())的生存期将达到语句(;)的末尾,因此可以通过非const引用将其传递给我的operator <<。 If it isn't so, could you tell me why?
如果不是这样,您能告诉我为什么吗?
Thanks. 谢谢。
The standard says that temporary objects may not be converted to non-const lvalue references implicitly. 该标准说临时对象可能不会隐式转换为非常量左值引用。 See [dcl.init.ref]/8.6.3.5.2 in n4628.
请参阅n4628中的[dcl.init.ref] /8.6.3.5.2。
Otherwise, the reference shall be an lvalue reference to a non-volatile const type (ie, cv1 shall be const), or the reference shall be an rvalue reference.
否则,该引用应为对非易失性const类型的左值引用(即cv1为const),或者该引用应为右值引用。 [ Example:
[示例:
double& rd2 = 2.0; // error: not an lvalue and reference not const int i = 2; double& rd3 = i; // error: type mismatch and reference not const
— end example ]
—结束示例]
To solve this: 要解决这个问题:
template<class T>
T& as_lvalue(T&&t){return t;}
This function takes an rvalue t
and returns an lvalue reference. 此函数取一个右值
t
并返回一个左值引用。
as_lvalue(NS::B()) << 2.71 << 123 << "abcdef";
The above is both standard compliant and safe. 以上内容均符合标准且安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.