我是否正确地说 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 限定types(第 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 常量.这是一个顶级常量(在对象上),所以任何尝试修改它是未定义的行为.

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.

相关文章