我说 const_cast 然后修改绑定到临时对象的 ref-to-const 是对的吗?

我想检查一下我对此事的理解和结论.

I would like to check my understanding and conclusions on this matter.

在 IRC 上,有人问:

On IRC, it was asked:

const_cast 是否可以接受绑定到临时对象的 const 引用?

Is it acceptable to const_cast a const reference that's bound to a temporary object?

翻译:他有一个 ref-to-const 绑定到一个临时对象,他想抛弃它的 const-ness 来修改它.

Translating: he has a ref-to-const bound to a temporary, and he wants to cast away its const-ness to modify it.

我的回答是我问了a之前类似的问题,其中的共识似乎是临时变量本身并不是固有的 const,因此您可以摆脱引用的 const-ness你必须对它们,并通过结果修改它们.而且,只要那个原始的 ref-to-const 仍然存在,这不会影响临时的生命周期.

My response was that I'd asked a similar question previously, where the consensus seemed to be that temporaries themselves are not inherently const, and thus that you can cast off the const-ness of a reference you have to them, and modify them through the result. And, as long as that original ref-to-const still exists, this won't affect the temporary's lifetime.

即:

int main()
{
   const int& x = int(3);

   int& y = const_cast<int&>(x);
   y = 4;

   cout << x;
}
// Output: 4
// ^ Legal and safe

我说得对吗?

(当然,这样的代码是否可行完全是另一回事!)

推荐答案

没有

首先,据我所知,它是否是文字是无关.非类类型的右值总是有非 cv 限定类型(第 3.10/9 节),但是,在第 8.5.3 节(引用的初始化)中,我们有:

First, as far as I can tell, whether it is a literal or not is irrelevant. Rvalues of non-class types always have non-cv qualified types (§3.10/9), however, in §8.5.3 (initialization of a reference), we have:

对cv1 T1"类型的引用由cv2 T2"类型的表达式初始化,如下所示:

A reference to type "cv1 T1" is initialized by an expression of type "cv2 T2" as follows:

[...]

--

否则,将使用非引用复制初始化规则 (8.5) 从初始化表达式创建和初始化类型为cv1 T1"的临时对象.然后将引用绑定到临时对象.如果 T1 与 T2 引用相关,则 cv1 必须与 cv-qualification 相同或更高比,cv2;否则,程序格式错误.

Otherwise, a temporary of type "cv1 T1" is created and initialized from the initializer expression using the rules for a non-reference copy initialization (8.5). The reference is then bound to the temporary. If T1 is reference-related to T2, cv1 must be the same cv-qualification as, or greater cvqualification than, cv2; otherwise, the program is ill-formed.

(以上所有点都涉及左值或类类型.)

(All of the preceding points concern either lvalues or class types.)

在我们的例子中,我们有:

In our case, we have:

int const& x = ...;

所以cv1 T1是int const,我们创建的临时对象有类型int const.这是一个顶级常量(在对象上),所以任何尝试修改它是未定义的行为.

So cv1 T1 is int const, and the temporary object we create has type int const. This is a top level const (on the object), so any attempt to modify it is undefined behavior.

至少,这是我的解释.我希望标准能更清楚地说明这一点.

At least, that's my interpretation. I wish the standard were a bit clearer about this.

相关文章