Why does an lvalue cast work?

此生再无相见时 提交于 2019-11-26 22:09:26

问题


I saw this kind of cast for the first time today, and I'm curious as to why this works. I thought casting in this manner would assign to the temporary, and not the class member. Using VC2010.

class A
{
public:

   A() :
      m_value(1.f)
   {
      ((float)m_value) = 10.f;
   }

   const float m_value;
};

回答1:


It shouldn't work. An explicit type conversion to float with cast notation will be a prvalue (§5.4):

The result of the expression (T) cast-expression is of type T. The result is an lvalue if T is an lvalue reference type or an rvalue reference to function type and an xvalue if T is an rvalue reference to object type; otherwise the result is a prvalue.

My emphasis added.

The assignment operator requires an lvalue as its left operand (§5.17):

All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand.

A prvalue is not an lvalue.




回答2:


Even after fixing all other problems to make the code compile, it only works in VC2010 because it uses a non-standard extension. And If you specify /Wall to see all warnings, you compiler will emit

warning C4213: nonstandard extension used : cast on l-value



来源:https://stackoverflow.com/questions/15343276/why-does-an-lvalue-cast-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!