转换指针不会产生左值.为什么? [英] Casting a pointer does not produce an lvalue. Why?

查看:37
本文介绍了转换指针不会产生左值.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处发布我最有争议的答案之一后,我敢问几个问题,最终填补了我的一些知识空白.

为什么 ((type_t *) x) 类型的表达式不被认为是有效的左值,假设 x 本身是一个指针和一个左值,而不是只是一些表达?

我知道很多人会说标准不允许",但从逻辑的角度来看,这似乎是合理的.标准不允许的原因是什么?毕竟,任何两个指针的大小都相同,指针类型只是一个编译时抽象,表示在进行指针运算时应该应用适当的偏移量.

解决方案

一个更好的例子,一元 + 产生一个右值,x+0 也是如此.

根本原因是所有这些东西,包括你的演员阵容,都创造了一个新的价值.将一个值转换为它已经存在的类型,同样会创建一个新值,不管指向不同类型的指针是否具有相同的表示形式.在某些情况下,新值恰好等于旧值,但原则上它是一个新值,它不打算用作旧对象的引用,这就是它是右值的原因.

为了使这些成为左值,标准必须添加一些特殊情况,即在左值上使用某些操作时会导致对旧对象的引用,而不是新值.AFAIK 对这些特殊情况的需求不大.

After posting one of my most controversial answers here, I dare to ask a few questions and eventually fill some gaps in my knowledge.

Why isn't an expression of the kind ((type_t *) x) considered a valid lvalue, assuming that x itself is a pointer and an lvalue, not just some expression?

I know many will say "the standard disallows it", but from a logical standpoint it seems reasonable. What is the reason that the standard disallows it? After all, any two pointers are of the same size and the pointer type is just a compile-time abstraction that indicates the appropriate offset that should be applied when doing pointer arithmetic.

解决方案

An even better example, unary + yields an rvalue, as does x+0.

The underlying reason is that all these things, including your cast, create a new value. Casting a value to the type it already is, likewise creates a new value, never mind whether pointers to different types have the same representation or not. In some cases, the new value happens to be equal to the old value, but in principle it's a new value, it's not intended to be used as a reference to the old object, and that's why it's an rvalue.

For these to be lvalues, the standard would have to add some special cases that certain operations when used on an lvalue result in a reference to the old object, instead of a new value. AFAIK there's no great demand for those special cases.

这篇关于转换指针不会产生左值.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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